#include #include #include //for bzero #include #include #include #include using namespace std; int main(int argc, char **argv) { //file descriptor for accepting a client const int s = socket(AF_INET, SOCK_STREAM, 0); if (s < 0) { perror(argv[0]); return 1; } int reuseaddr = 1; if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof reuseaddr) != 0) { perror(argv[0]); return 2; } reuseaddr = 0; size_t opt_length = sizeof reuseaddr; if (getsockopt(s, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, &opt_length) != 0) { perror(argv[0]); return 3; } cout << "The SO_REUSEADDR option of the socket is " << reuseaddr << ".\n"; //In real life, the TCP/IP echo server is always bound to port 7, //not port 3000. struct sockaddr_in serveraddress; bzero(&serveraddress, sizeof serveraddress); serveraddress.sin_family = AF_INET; serveraddress.sin_port = htons(3000); serveraddress.sin_addr.s_addr = INADDR_ANY; if (bind(s, reinterpret_cast(&serveraddress), sizeof serveraddress) != 0) { perror(argv[0]); return 4; } if (listen(s, SOMAXCONN) != 0) { perror(argv[0]); return 5; } struct sockaddr_in clientaddress; socklen_t length = sizeof clientaddress; //file descriptor for talking to client const int client = accept(s, reinterpret_cast(&clientaddress), &length); if (client < 0) { perror(argv[0]); return 6; } char dotted[INET6_ADDRSTRLEN]; if (inet_ntop(AF_INET, &clientaddress.sin_addr, dotted, sizeof dotted) == NULL) { perror(argv[0]); return 7; } cout << "I have accepted a client whose IP address is " << dotted << ".\n"; //The service provided by this server is to input and output one //character. char c; if (read(client, &c, 1) != 1) { perror(argv[0]); return 8; } if (write(client, &c, 1) != 1) { perror(argv[0]); return 9; } if (shutdown(client, SHUT_RDWR) != 0) { perror(argv[0]); return 10; } return EXIT_SUCCESS; }