/*-------------------------------------------------------------------*/ /* client.c */ /* A client that uses sockets. */ /*-------------------------------------------------------------------*/ #include #include #include #include #include #include #include FILE *fdopen(int fildes, const char *mode); #define BUFFER_LENGTH 100 int main(int argc, char *argv[]) /* Connect to a server whose name is argv[1] at port argv[2]. Read a name from stdin, write that name to the server, read a greeting that contains that name from the server, and write the greeting to stdout. */ { int iRet; int iSocketFd; struct sockaddr_in sSocketAddr; struct hostent *psHostEntity; int iPort; if (argc != 3) { fprintf(stderr, "Usage: %s host port\n", argv[0]); return 1; } iRet = sscanf(argv[2], "%d", &iPort); if (iRet != 1) { fprintf(stderr, "Error: Port must be numeric\n"); return 2; } /* Given the server host name, get the server host address. */ psHostEntity = gethostbyname(argv[1]); if (psHostEntity == NULL) { fprintf(stderr, "Error: Unknown host\n"); return 3; } /* Create a socket, that is, an endpoint for communication with the server that is identified by a file descriptor. */ iSocketFd = socket(AF_INET, SOCK_STREAM, 0); if (iSocketFd == -1) { fprintf(stderr, "Error: Failed to create socket\n"); return 4; } /* Given the server IP address, the server port, and the socket, request a connection to the server through the socket. */ memcpy((char*)&sSocketAddr.sin_addr, psHostEntity->h_addr_list[0], psHostEntity->h_length); sSocketAddr.sin_family = AF_INET; sSocketAddr.sin_port = htons((short)iPort); iRet = connect(iSocketFd, (struct sockaddr*)(&sSocketAddr), sizeof(sSocketAddr)); if (iRet == -1) { perror(argv[0]); close(iSocketFd); return 5; } /* Communicate with the server via the file descriptor using either low-level I/O functions (write and read) or standard I/O functions. */ { char pcPersonName[BUFFER_LENGTH]; char pcGreeting[BUFFER_LENGTH]; FILE *psFile; /* Wrap a FILE structure around the file descriptor to enable subsequent use of standard I/O functions. */ psFile = fdopen(iSocketFd, "w+"); if (psFile == NULL) { perror(argv[0]); close(iSocketFd); return 7; } /* Write and read data. */ fputs("Name: ", stdout); fgets(pcPersonName, BUFFER_LENGTH, stdin); fputs(pcPersonName, psFile); fflush(psFile); fgets(pcGreeting, BUFFER_LENGTH, psFile); fputs(pcGreeting, stdout); fclose(psFile); } return 0; }