/* Bryce's Chat1 Program * Based on Beej's: ** server.c -- a stream socket server demo ** (Simplified to remove forking.) * * Usage: supply the port to be used on the command line. */ #include #include #include #include #include #include #include #include #include #define BACKLOG 10 // how many pending connections queue will hold int main(int argc, char *argv[]) { int sockfd, new_fd; // listen on sock_fd, new connection on new_fd struct sockaddr_in my_addr; // my address information struct sockaddr_in their_addr; // connector's address information socklen_t sin_size; char buffer[128] = ""; /* Buffer for reading from client. */ int yes=1; int port = 41000; if (argc < 2) { printf("Error: specify the port number on the command line.\n"); exit(1); } if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); exit(1); } if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("setsockopt"); exit(1); } port = atoi(argv[1]); my_addr.sin_family = AF_INET; // host byte order my_addr.sin_port = htons(port); // short, network byte order my_addr.sin_addr.s_addr = INADDR_ANY; // automatically fill with my IP memset(my_addr.sin_zero, '\0', sizeof my_addr.sin_zero); if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof my_addr) == -1) { perror("bind"); exit(1); } if (listen(sockfd, BACKLOG) == -1) { perror("listen"); exit(1); } printf("Server serving. Press ^C to quit.\n"); while(1) { // main accept() loop sin_size = sizeof their_addr; if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size)) == -1) { perror("accept"); continue; } printf("server: got connection from %s\n", \ inet_ntoa(their_addr.sin_addr)); if (send(new_fd, "connected\n", 11, 0) == -1) perror("send"); if (recv(new_fd, buffer, 127, 0) == -1) perror("recv"); printf("Got from client: %s\n",buffer); if (send(new_fd, buffer, strlen(buffer)+1, 0) == -1) perror("echo"); printf("Echoed and disconnected.\n"); close(new_fd); } return 0; }