/********************************************************************\ Example socket server Code from original drsdaq socket thread This code will block execution in the accept() and read() socket function while waiting for a connection or data. To terminate, these blocking functions must be interrupted by raising a signal (e.g. SIGUSR1). Testing on errno=EINTR then indicates this. Oliver Grimm, May 2010 \********************************************************************/ #define PORT 2000 // TCP/IP port void CCCommand() { int ServerSocket,ConnectionSocket,ReadResult; struct sockaddr_in SocketAddress, ClientAddress; struct hostent *ClientName; socklen_t SizeClientAddress=sizeof(ClientAddress); char Command[MAX_COM_SIZE]; // Set up server socket if ((ServerSocket = socket(PF_INET, SOCK_STREAM, 0)) == -1) { printf("Could not open server socket (%s)\n", strerror(errno)); return; } // Allows immediate reuse of socket after closing (circumvents TIME_WAIT) int Value=1; if (setsockopt(ServerSocket, SOL_SOCKET, SO_REUSEADDR, (char *) &Value, sizeof (Value)) == -1) { printf("Warning: Could not set server socket option SO_REUSEADDR (%s)\n", strerror(errno)); } SocketAddress.sin_family = PF_INET; SocketAddress.sin_port = htons((unsigned short) PORT); SocketAddress.sin_addr.s_addr = INADDR_ANY; if (bind(ServerSocket, (struct sockaddr *) &SocketAddress, sizeof(SocketAddress)) == -1) { printf("Could not bind port to socket (%s)\n", strerror(errno)); close(ServerSocket); return; } if (listen(ServerSocket, 0) == -1) { printf("Could not set socket to listening (%s)\n", strerror(errno)); close(ServerSocket); return; } // Looping to wait for incoming connection while (true) { if ((ConnectionSocket = accept(ServerSocket, (struct sockaddr *) &ClientAddress, &SizeClientAddress)) == -1) { if (errno!=EINTR) printf("Failed to accept incoming connection (%s)\n", strerror(errno)); close(ServerSocket); return; } ClientName = gethostbyaddr((char *) &ClientAddress.sin_addr ,sizeof(struct sockaddr_in),AF_INET); printf("Connected to client at %s (%s).\n", inet_ntoa(ClientAddress.sin_addr), ClientName!=NULL ? ClientName->h_name:"name unknown"); // Looping as long as client exists and program not terminated while (true) { // Try to read command from socket memset(Command, 0, sizeof(Command)); ReadResult = read(ConnectionSocket, Command, MAX_COM_SIZE); if (ReadResult == 0) break; // Client not exisiting anymore if (ReadResult == -1) { if (errno!=EINTR) printf("Error read from socket (%s)\n", strerror(errno)); break; } if (Command[strlen(Command)-1]=='\n') Command[strlen(Command)-1]='\0'; // Remove trailing newline printf("Received command '%s'\n", Command); } printf("Disconnected from client.\n"); close(ConnectionSocket); } close(ServerSocket); printf("Server socket closed.\n"); }