/* ** client.c ** Presented in COMS3200 Lecture, 19 August 2005. ** Written by Peter Sutton. ** improved by Wei Yin 2011 ** Compile with "gcc -o client client.c" */ #include #include #include #include #include #include #include #include /* We ignore error handling and do not check the return values from system ** calls */ int main(int argc, char* argv[]) { int fd; struct in_addr* ipAddress; struct hostent* hostp; struct sockaddr_in socketAddr; char buffer[1024]; int numBytes; int serv_port; if(argc!=2) { fprintf(stderr,"Usage: %s server_port\n", argv[0]); exit(1); } serv_port = atoi(argv[1]); if(serv_port < 1024 || serv_port > 65535) { fprintf(stderr, "Invalid port number: %s\n", argv[1]); exit(1); } hostp = gethostbyname("localhost"); ipAddress = (struct in_addr*)hostp->h_addr_list[0]; /* Specify the address we're going to connect to */ socketAddr.sin_family = AF_INET; /* Internet socket */ socketAddr.sin_port = htons(serv_port); /* Port number in network byte order */ socketAddr.sin_addr.s_addr = ipAddress->s_addr; /* Copies IP address */ /* Create TCP socket */ fd = socket(AF_INET, SOCK_STREAM, 0); /* Try to connect to our server address */ /* Address cast to generic socket address type, but we need to specify ** the size of the address as the third argument */ connect(fd, (struct sockaddr*)&socketAddr, sizeof(socketAddr)); /* Read lines from standard input and send them to our server. Continue ** until standard input closes */ while(fgets(buffer, 1024, stdin)) { write(fd, buffer, strlen(buffer)); /* Wait for a reply */ numBytes = read(fd, buffer, 1023); /* Null terminate buffer */ buffer[numBytes] = '\0'; /* Print out reply to standard output */ printf("%s", buffer); fflush(stdout); } close(fd); return 0; }