Simple Linux client-server network program

Source: Internet
Author: User
Tags htons

In the following program, the server listens to port 5000. After the client connects to the server over TCP, the server will send the "Hello, success" string to the client. The program is very simple, but implements basic functions.

The server program is as follows:

# Include <sys/socket. h>
# Include <netinet/in. h>
Int main ()
...{
Int listensock, connsock;
Const char buff [] = "Hello, success ";
Struct sockaddr_in serveraddr;
Bzero (& serveraddr, sizeof (serveraddr ));
Listensock = socket (af_inet, sock_stream, 0 );
Serveraddr. sin_family = af_inet;
Serveraddr. sin_addr.s_addr = htonl (inaddr_any );
Serveraddr. sin_port = htons (5000 );
BIND (listensock, (struct sockaddr *) & serveraddr, sizeof (serveraddr ));
Printf ("begin to listen on port 5000 ...");
Listen (listensock, 1024 );
Connsock = accept (listensock, null, null );
Send (connsock, buff, sizeof (buff), 0 );
Close (connsock );
Close (listensock );

}

The client program is as follows:

# Include <sys/socket. h>
# Include <netinet/in. h>
Int main (INT argc, char * argv [])
...{
Int sockfd;
Char buffer [100];
Struct sockaddr_in serveraddr;
Bzero (& serveraddr, sizeof (serveraddr ));
Serveraddr. sin_family = af_inet;
Serveraddr. sin_port = htons (5000 );
Inet_ton (af_inet, "192.168.9.9", & serveraddr. sin_addr );
Sockfd = socket (af_inet, sock_stream, 0 );
Int value = connect (sockfd, (struct sockaddr *) & serveraddr, sizeof (serveraddr ));
If (value = 0)
Printf ("Connect succeed ");
Else
Printf ("Connect failed ");

Recv (sockfd, buffer, sizeof (buffer), 0 );
Printf ("% s", buffer );
Close (sockfd );
}

 

 

 

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.