summaryrefslogtreecommitdiff
path: root/src/main.c
blob: a1825d66c5e32fd3226b2606a5848933c67f8208 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>

int main() {
  struct sockaddr_in addr;
  addr.sin_family = AF_INET;         /* IPv4 */
  addr.sin_port = htons(8000);       /* Port */
  addr.sin_addr.s_addr = INADDR_ANY; /* equals to 0.0.0.0 */
  int sfd = socket(AF_INET, SOCK_STREAM, 0);
  if (sfd == -1) {
    perror("could not open socket");
    return 1;
  }
  int opt = 1;
  setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  int bind_addr = bind(sfd, (struct sockaddr *)&addr, sizeof(addr));
  if (bind_addr == -1) {
    perror("could not bind socket");
    return 1;
  }
  int listen_addr = listen(sfd, 100);
  if (listen_addr == -1) {
    perror("could not listen");
    return 1;
  }
  struct pollfd fds[256];
  fds[0].fd = sfd;        /* socket file descriptor */
  fds[0].events = POLLIN; /* data to read */
  nfds_t nfds = 1;        /* non file descriptor. something with timeout */
  while (1) {
    /* we start the polling here */
    int ready =
        poll(fds, nfds, -1); /* poll to accept many conn simultaneously */
    if (ready == -1) {
      perror("could not run poll");
      return 1;
    }
    char buf[1024];
    ssize_t n;
    while ((n = read(conn, buf, sizeof(buf))) > 0) {
      write(conn, buf, n);
    }
  }
  return 0;
}