oxedyne/fe2o3/fe2o3_text/tests/detect_corpus/c/socket_io.txt
1.7 KiB, 1 run
created by r1870400018:11942, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | #include <stdio.h> |
| 2 | #include <stdlib.h> |
| 3 | #include <string.h> |
| 4 | #include <unistd.h> |
| 5 | #include <sys/socket.h> |
| 6 | #include <netinet/in.h> |
| 7 | #include <arpa/inet.h> |
| 8 | |
| 9 | #define LISTEN_PORT 8080 |
| 10 | #define BACKLOG 16 |
| 11 | #define BUF_SIZE 4096 |
| 12 | |
| 13 | static int create_listener(uint16_t port) { |
| 14 | int fd = socket(AF_INET, SOCK_STREAM, 0); |
| 15 | if (fd < 0) { perror("socket"); exit(1); } |
| 16 | |
| 17 | int opt = 1; |
| 18 | setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); |
| 19 | |
| 20 | struct sockaddr_in addr; |
| 21 | memset(&addr, 0, sizeof(addr)); |
| 22 | addr.sin_family = AF_INET; |
| 23 | addr.sin_addr.s_addr = htonl(INADDR_ANY); |
| 24 | addr.sin_port = htons(port); |
| 25 | |
| 26 | if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) { |
| 27 | perror("bind"); |
| 28 | close(fd); |
| 29 | exit(1); |
| 30 | } |
| 31 | |
| 32 | if (listen(fd, BACKLOG) < 0) { |
| 33 | perror("listen"); |
| 34 | close(fd); |
| 35 | exit(1); |
| 36 | } |
| 37 | |
| 38 | return fd; |
| 39 | } |
| 40 | |
| 41 | static void handle_client(int client_fd) { |
| 42 | char buf[BUF_SIZE]; |
| 43 | ssize_t n; |
| 44 | |
| 45 | while ((n = read(client_fd, buf, sizeof(buf) - 1)) > 0) { |
| 46 | buf[n] = '\0'; |
| 47 | printf("received: %s", buf); |
| 48 | write(client_fd, buf, n); |
| 49 | } |
| 50 | |
| 51 | close(client_fd); |
| 52 | } |
| 53 | |
| 54 | int main(void) { |
| 55 | int listen_fd = create_listener(LISTEN_PORT); |
| 56 | printf("listening on port %d\n", LISTEN_PORT); |
| 57 | |
| 58 | for (;;) { |
| 59 | struct sockaddr_in client_addr; |
| 60 | socklen_t addr_len = sizeof(client_addr); |
| 61 | int client_fd = accept(listen_fd, (struct sockaddr *)&client_addr, &addr_len); |
| 62 | if (client_fd < 0) { |
| 63 | perror("accept"); |
| 64 | continue; |
| 65 | } |
| 66 | |
| 67 | printf("connection from %s:%d\n", |
| 68 | inet_ntoa(client_addr.sin_addr), |
| 69 | ntohs(client_addr.sin_port)); |
| 70 | |
| 71 | handle_client(client_fd); |
| 72 | } |
| 73 | |
| 74 | close(listen_fd); |
| 75 | return 0; |
| 76 | } |