This example is a client/server structure that demonstrates how the client establishes a connection and sends data to the remote end, how the Server listens to the system connection request, receives the request and establishes the connection, and obtains the data from the client. Although the code is short, but describes the entire communication process, Linux can be programmed under the network to play a role bar:-)
/* Init sockaddr_in * *
my_addr.sin_family = af_inet; /* Note: Host byte order should be used * *
My_addr.sin_port = htons (MyPort); /* Note: network byte order should be used * *
MY_ADDR.SIN_ADDR.S_ADDR = htonl (Inaddr_any); /* Use your own IP address */
Bzero (& (My_addr.sin_zero), 8); /* The rest of the structure must be placed 0*/
/* Specify the address and port to use for a socket * *
res = bind (SOCKFD, (struct sockaddr*) &my_addr, sizeof (struct sockaddr));
if (res = = 1) {
Perror ("bind");
Exit (1);
}
/* Listening request, waiting for connection * *
res = Listen (SOCKFD,
BACKLOG); /* The maximum number of unhandled connection request queues to hold * *
if (res = = 1) {
Perror ("Listen");
Exit (1);
}
/* Accept each other's connection request, establish a connection, and return a new connection descriptor.
* and the first socket descriptor is still on your machine the original port listen ()
*/
sin_size = sizeof (struct sockaddr_in);
NEW_FD = Accept (SOCKFD, (void *) &their_addr, &sin_size);
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.