Main function:
# Include " Unp. h "
Int Main ( Int Argc, Char ** Argv)
{
Int Sockfd;
Struct Sockaddr_in servaddr;
If (Argc! = 2 )
Err_quit (" Usage: tcpcli <IPaddress> " );
/* Socket function prototype: int socket (INT family, int type, int Protocol); When protocol is 0
To select the default value for the combination of family and type. Refer to section 4.2, */
Sockfd = socket (af_inet, sock_stream, 0 );
Bzero (& servaddr, Sizeof (Servaddr ));
Servaddr. sin_family = af_inet;
/* Consider the mutual conversion between host byte order and network byte. Refer to section 3.4 */
Servaddr. sin_port = htons (serv_port );
/* Address Conversion Function inet_ton (INT, const char *, void *): converts an IPv4 address in decimal format to a 32-bit binary IPv4 address. Section 3.7 */
Inet_ton (af_inet, argv [ 1 ], & Servaddr. sin_addr );
/* Establish a connection with the server */
Connect (sockfd, (Sa *) & servaddr, Sizeof (Servaddr ));
Str_cli (stdin, sockfd ); /* Do it all */
Exit ( 0 );
}
Str_cli functions:
This function completes the customer processing cycle: reads a line of text from the standard input, writes it to the server, reads the server's response to the line of text, and writes the response row to the standard output.
# Include " Unp. h "
Void
Str_cli (File * FP, Int Sockfd)
{
Char Sendline [maxline], recvline [maxline];
/* Fgets reads a line of text */
While (Fgets (sendline, maxline, FP )! = NULL ){
/* Send this line of text to the server */
Writen (sockfd, sendline, strlen (sendline ));
/* Readline reads the echo row from the server */
If (Readline (sockfd, recvline, maxline) = 0 )
Err_quit ( " Str_cli: Server terminated prematurely " );
/* Fputs writes the echo row to the standard output. */
Fputs (recvline, stdout );
}
}