A simple network program source code for beginners

Source: Internet
Author: User
Here is a simple network program source code for beginners-Linux general technology-Linux programming and kernel information. Send new users a simple server and client code for them to learn.

Server Source Code:
# Include
# Include
# Include
# Include
# Include
# Include
# Include

# Deprecision MAX_LINE 100

Void my_fun (char * p)
{
If (p = NULL)
Return;

For (; * p! = '\ 0'; p ++)
If (* p> = 'A' & * p <= 'Z ')
* P = * p-'A' + 'a ';
}
Int main (void)
{
Struct sockaddr_in sin;
Struct sockaddr_in cin;
Int l_fd;
Int c_fd;
Socklen_t len;
Char buf [MAX_LINE];
Char addr_p [INET_ADDRSTRLEN];
Int port = 8000;
Int n;

Bzero (& sin, sizeof (sin ));
Sin. sin_family = AF_INET;
Sin. sin_addr.s_addr = INADDR_ANY;
Sin. sin_port = htons (port );
L_fd = socket (AF_INET, SOCK_STREAM, 0 );
Bind (l_fd, (struct sockaddr *) & sin, sizeof (sin ));
Listen (l_fd, 10 );
Printf ("waiting... \ n ");

While (1)
{
C_fd = accept (l_fd, (struct sockaddr *) & cin, & len );
N = read (c_fd, buf, MAX_LINE );
Inet_ntop (AF_INET, & cin. sin_addr, addr_p, sizeof (addr_p ));
Printf ("client ip is % s, port is % d \ n", addr_p, ntohs (cin. sin_port ));
Printf ("content is: % s \ n", buf );
My_fun (buf );
Write (c_fd, buf, n );
Close (c_fd );
}
If (close (l_fd) =-1)
{
Perror ("fail to close \ n ");
Exit (1 );
}
Return 0;
}

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.