|
| 1 | +#include <stdio.h> |
| 2 | +#include <stdlib.h> |
| 3 | +#include <sys/socket.h> |
| 4 | +#include <netinet/in.h> |
| 5 | +#include <netinet/ip.h> |
| 6 | +#include <string.h> |
| 7 | +#include <errno.h> |
| 8 | +#include <unistd.h> |
| 9 | + |
| 10 | +int main(int argc, char* argv[]) { |
| 11 | + // Disable output buffering |
| 12 | + setbuf(stdout, NULL); |
| 13 | + setbuf(stderr, NULL); |
| 14 | + |
| 15 | + int server_fd, client_addr_len; |
| 16 | + struct sockaddr_in client_addr; |
| 17 | + |
| 18 | + server_fd = socket(AF_INET, SOCK_STREAM, 0); |
| 19 | + if (server_fd < 0) { |
| 20 | + printf("Socket creation failed: %s...\n", strerror(errno)); |
| 21 | + return 1; |
| 22 | + } |
| 23 | + |
| 24 | + // Since the tester restarts your program quite often, setting SO_REUSEADDR |
| 25 | + // ensures that we don't run into 'Address already in use' errors |
| 26 | + int reuse = 1; |
| 27 | + if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0) { |
| 28 | + printf("SO_REUSEADDR failed: %s \n", strerror(errno)); |
| 29 | + return 1; |
| 30 | + } |
| 31 | + |
| 32 | + struct sockaddr_in serv_addr = { |
| 33 | + .sin_family = AF_INET, |
| 34 | + .sin_port = htons(9092), |
| 35 | + .sin_addr = { htonl(INADDR_ANY) }, |
| 36 | + }; |
| 37 | + |
| 38 | + if (bind(server_fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) != 0) { |
| 39 | + printf("Bind failed: %s \n", strerror(errno)); |
| 40 | + return 1; |
| 41 | + } |
| 42 | + |
| 43 | + int connection_backlog = 5; |
| 44 | + if (listen(server_fd, connection_backlog) != 0) { |
| 45 | + printf("Listen failed: %s \n", strerror(errno)); |
| 46 | + return 1; |
| 47 | + } |
| 48 | + |
| 49 | + printf("Waiting for a client to connect...\n"); |
| 50 | + client_addr_len = sizeof(client_addr); |
| 51 | + |
| 52 | + // You can use print statements as follows for debugging, they'll be visible when running tests. |
| 53 | + printf("Logs from your program will appear here!\n"); |
| 54 | + |
| 55 | + // TODO: Uncomment the code below to pass the first stage |
| 56 | + // |
| 57 | + // int client_fd = accept(server_fd, (struct sockaddr *) &client_addr, &client_addr_len); |
| 58 | + // printf("Client connected\n"); |
| 59 | + // close(client_fd); |
| 60 | + |
| 61 | + close(server_fd); |
| 62 | + return 0; |
| 63 | +} |
0 commit comments