#include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; int main(int argc, char* argv[]) { if (argc < 2) { printf("Syntax: client
\n"); exit(-1); } //Create a socket int client_sock = socket(AF_INET, SOCK_STREAM, 0); if (client_sock < 0) { perror("socket"); exit(-1); } //Create an address structure for binding to the "wildcard "ddress struct sockaddr_in addr; bzero(&addr, sizeof(sockaddr_in)); addr.sin_family = AF_INET; //Convert the first command line argument to an address struct inet_pton(AF_INET, argv[1], &addr.sin_addr); //Get the port from the command line int port = atoi(argv[2]); addr.sin_port = htons(port); //Connect to the server int result = connect(client_sock, (struct sockaddr *)&addr, sizeof(addr)); if (result < 0) { perror("connect"); close(client_sock); exit(-1); } int pid = fork(); if (pid == 0) { char* buf = new char[1024]; size_t size = 1024; while ( getline(&buf, &size, stdin) >= 0) { int bytes = write(client_sock, buf, strlen(buf)); if (bytes < 0) { perror("write"); break; } size = 1024; } close(client_sock); } else { while (1) { char buf[1025]; int bytes = read(client_sock, buf, 1024); buf[bytes] = 0; printf("%s\n", buf); } } }