Theoretical Basis of set Interface Programming: TCP shot-back client program

Source: Internet
Author: User

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 );
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.