/* * echo-server.c */ #include #include #include #include #include #include #include #include #include #define BACKLOG 10 #define BUF_SIZE 4096 int main(int argc, char *argv[]) { char *listen_port; int listen_fd, conn_fd; struct addrinfo hints, *res; int rc; struct sockaddr_in remote_sa; uint16_t remote_port; socklen_t addrlen; char *remote_ip; char buf[BUF_SIZE]; int bytes_received; listen_port = argv[1]; /* create a socket */ listen_fd = socket(PF_INET, SOCK_STREAM, 0); /* bind it to a port */ memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; if((rc = getaddrinfo(NULL, listen_port, &hints, &res)) != 0) { printf("getaddrinfo failed: %s\n", gai_strerror(rc)); exit(1); } bind(listen_fd, res->ai_addr, res->ai_addrlen); /* start listening */ listen(listen_fd, BACKLOG); /* infinite loop of accepting new connections and handling them */ while(1) { /* accept a new connection (will block until one appears) */ addrlen = sizeof(remote_sa); conn_fd = accept(listen_fd, (struct sockaddr *) &remote_sa, &addrlen); /* announce our communication partner */ remote_ip = inet_ntoa(remote_sa.sin_addr); remote_port = ntohs(remote_sa.sin_port); printf("new connection from %s:%d\n", remote_ip, remote_port); /* receive and echo data until the other end closes the connection */ while((bytes_received = recv(conn_fd, buf, BUF_SIZE, 0)) > 0) { printf("."); fflush(stdout); /* send it back */ send(conn_fd, buf, bytes_received, 0); } printf("\n"); close(conn_fd); } }