TCP/IP Programming Manual
char request[MAXBUFSIZE] = " This is the client's request";
if (argc < 2) {
printf("Usage: client <server>\n");
exit (0);
}
server = argv[1];
/* Clear the server address and sets up server variables.
The socket address is a 32-bit Internet address and a 16-bit
port number. */
bzero((char *) &serveraddr, sizeof(struct sockaddr_in));
serveraddr.sin_family = AF_INET;
/* Obtain the server's IPv4 address. A call to gethostbyname
returns IPv4 address only. */
if ((hp = gethostbyname(server)) == NULL) {
printf("unknown host: %s\n", server);
exit(2);
}
serveraddr.sin_port = htons(SERVER_PORT);
/* Creates an AF_INET socket with a socket call. The socket type
SOCK_STREAM is specified for TCP or connection-oriented
communication. */
while (hp->h_addr_list[0] != NULL) {
if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("socket");
exit(3);
}
memcpy(&serveraddr.sin_addr.s_addr, hp->h_addr_list[0],
hp->h_length);
/* Connect to the server using the address in the sockaddr_in
structure named serveraddr. */
if ((error = connect(s, (struct sockaddr *)&serveraddr,
sizeof(serveraddr)) ) < 0) {
perror("connect");
hp->h_addr_list++;
continue;
}
break;
}
if (error < 0)
exit(4);
/* Send a request to the server. */
if (send(s, request, (int)strlen(request), 0) < 0) {
perror("send");
exit(5);
}
/* Receive a response from the server. */
dcount = recv(s, databuf, sizeof(databuf), 0);
if (dcount < 0) {
perror("recv");
exit(6);
}
databuf[dcount] = '\0';
/* Get the server name using the address in the sockaddr_in
structure named serveraddr. A call to gethostbyaddrexpects an
IPv4 address as input. */
hp = gethostbyaddr((char *)&serveraddr.sin_addr.s_addr,
sizeof(serveraddr.sin_addr.s_addr), AF_INET);
Programs Using AF_INET Sockets 209