#include #include #include //for bzero #include //for getservbyname, h_errno #include //for socket #include //for inet_ntop using namespace std; int main(int argc, char **argv) { //file descriptor for talking to server const int s = socket(AF_INET, SOCK_STREAM, 0); if (s < 0) { perror(argv[0]); return 1; } //In real life, the TCP/IP echo server is always bound to port 7, //not port 3000. struct sockaddr_in address; bzero(&address, sizeof address); address.sin_family = AF_INET; address.sin_port = htons(3000); //Change the string "localhost" to an IP address. struct hostent *entry = gethostbyname("localhost"); if (entry == 0) { cerr << argv[0] << ": gethostbyname, h_errno == " << h_errno << "\n"; return 2; } address.sin_addr.s_addr = *reinterpret_cast(entry->h_addr_list[0]); //Print the IP address as a string of numbers with dots. char buffer[INET_ADDRSTRLEN]; if (inet_ntop(AF_INET, &address.sin_addr, buffer, sizeof buffer) == 0) { perror(argv[0]); return 3; } cout << "Trying " << buffer << "...\n"; //Try to connect to the echo server. if (connect(s, reinterpret_cast(&address), sizeof address) != 0) { perror(argv[0]); return 4; } //Print the hostname corresponding to the IP address. entry = gethostbyaddr(reinterpret_cast(&address.sin_addr), sizeof address.sin_addr, AF_INET); if (entry == NULL) { cerr << argv[0] << ": gethostbyaddr, h_errno == " << h_errno << "\n"; return 5; } cout << "Connected to " << entry->h_name << ".\n"; //Send one byte to the echo server. char c = 'A'; if (write(s, &c, 1) != 1) { perror(argv[0]); return 6; } //Get one byte from the echo server. c = '\0'; //Prove that there's nothing up my sleve. if (read(s, &c, 1) != 1) { perror(argv[0]); return 7; } cout << c << "\n"; if (shutdown(s, SHUT_RDWR) != 0) { perror(argv[0]); return 8; } return EXIT_SUCCESS; }