/********************************************************************** * server.c * * SERVER CODE * * from https://www.programminglogic.com/ * example-of-client-server-program-in-c-using-sockets-and-tcp/ * * ... with various minor modifications by Jim Mahoney on Nov 2018. *********************************************************************/ #include #include #include #include #include #include /* Pick a port to use for this client/server connection. The client will need to use this same port. It's an arbitrary number between 1024 and 65535 (16 bit unsigned). */ /* The low ports are reserved for system use; google "port numbers". */ #define PORT 7891 /* And pick an arbitrary number of connections which can be waiting. */ #define MAX_CONNECTIONS 5 #define BUFFER_SIZE 1024 /* localhost */ #define LOCALHOST "127.0.0.1" /* shannon.marlboro.college */ #define SHANNON "96.126.107.158" int main(){ char buffer[BUFFER_SIZE]; int listen_socket; int connect_socket; struct sockaddr_in address; struct sockaddr_storage storage; socklen_t address_size = sizeof(struct sockaddr_in); char* message = "The server says 'Hi there!'"; /*---- Create the socket. The three arguments are: ---- 1) Internet domain 2) Stream socket 3) Default protocol (TCP in this case) */ listen_socket = socket(PF_INET, SOCK_STREAM, 0); /*---- Configure settings of the server address struct ----*/ /* Address family = Internet */ address.sin_family = AF_INET; /* Set port number, using htons function to use proper byte order */ address.sin_port = htons(PORT); /* Set IP address to localhost */ /* address.sin_addr.s_addr = inet_addr(HOST); */ /* ... or shannon.marlboro.college */ address.sin_addr.s_addr = inet_addr(SHANNON); /* Set all bits of the padding field to 0 */ memset(address.sin_zero, '\0', sizeof(address.sin_zero)); /*---- Bind the address struct to the socket ----*/ bind(listen_socket, (struct sockaddr *) &address, sizeof(address)); /*-- Listen on the socket, with 5 max connection requests queued --*/ if(listen(listen_socket, MAX_CONNECTIONS)==0) { printf("Server: listening on port %d ...\n", PORT); }else { printf("Error!\n"); return 0; /* Something went wrong - bail out. */ } /*-- Accept call creates a new socket for the first queued connection. --*/ /* This is a "blocking call" - execution stops here and waits. */ /* See e.g. http://manpages.ubuntu.com/manpages/bionic/man2/accept.2.html */ connect_socket = accept(listen_socket, (struct sockaddr *) &storage, &address_size); printf("Server: connection established.\n"); /*---- Send message to the socket of the incoming connection ----*/ strcpy(buffer, message); send(connect_socket, buffer, strlen(message) + 1, 0); printf("Server: message sent.\n"); printf("Server exiting.\n"); close(connect_socket); close(listen_socket); return 0; }