Linux C language socket network programming example

Source: Internet
Author: User
Tags htons

The simple socket network programming instance in linux is provided here. The tcp protocol is used for communication. The server listens and sends data to the client after receiving the connection from the client; after receiving the data, the client prints the data and closes it. Detailed descriptions are provided in the program. For details about the implementation of struct and function, refer to other materials.

Program Description: here, the server port number and IP address are fixed settings. You can change the port number and IP address according to the specific situation during migration. It is better to change the port number and IP address to parameters for convenience.

During migration, the server does not need to be changed. After compilation, the server can run the program directly. The client changes the ip address to the server address and then compiles and runs the program. You can use netstat to view the corresponding running status.


[Cpp]
/*************************************
File Name: server. c
Socket network programming in linux-server programs
The server port is set to 0x8888 (the port and address can be changed according to the actual situation, or the parameter can be used for input)
Set the server address to 192.168.1.104.
Author: kikilizhm # 163.com (replace # @)
*/
 
# Include <stdlib. h>
# Include <sys/types. h>
# Include <stdio. h>
# Include <sys/socket. h>
# Include <linux/in. h>
# Include <string. h>
 
Int main ()
{
Int sfp, nfp;/* defines two descriptors */
Struct sockaddr_in s_add, c_add;
Int sin_size;
Unsigned short portnum = 0x8888;/* server port used */
 
Printf ("Hello, welcome to my server! \ R \ n ");
Sfp = socket (AF_INET, SOCK_STREAM, 0 );
If (-1 = sfp)
{
Printf ("socket fail! \ R \ n ");
Return-1;
}
Printf ("socket OK! \ R \ n ");
 
/* Fill in the server port address to use this address and port monitoring below */
Bzero (& s_add, sizeof (struct sockaddr_in ));
S_add.sin_family = AF_INET;
S_add.sin_addr.s_addr = htonl (INADDR_ANY);/* the address here is all 0, that is, all */
S_add.sin_port = htons (portnum );
/* Bind the port */
If (-1 = bind (sfp, (struct sockaddr *) (& s_add), sizeof (struct sockaddr )))
{
Printf ("bind fail! \ R \ n ");
Return-1;
}
Printf ("bind OK! \ R \ n ");
/* Start listening to the corresponding port */
If (-1 = listen (sfp, 5 ))
{
Printf ("listen fail! \ R \ n ");
Return-1;
}
Printf ("listen OK \ r \ n ");
 
While (1)
{
Sin_size = sizeof (struct sockaddr_in );
/* The accept server uses a function. When called, it is blocked. When the user is waiting for a connection, the program stops at this point when no client is connected,
The subsequent printing will not be seen. When a client is connected, the program will be executed immediately, and the loop will continue to wait here again.
The second accept parameter is used to obtain the port and address information of the client.
*/
Nfp = accept (sfp, (struct sockaddr *) (& c_add), & sin_size );
If (-1 = nfp)
{
Printf ("accept fail! \ R \ n ");
Return-1;
}
Printf ("accept OK! \ R \ nServer start get connect from % # x: % # x \ r \ n ", ntohl (c_add.sin_addr.s_addr), ntohs (c_add.sin_port ));
 
/* Use write to send information to the client, or use other functions */
If (-1 = write (nfp, "hello, welcome to my server \ r \ n", 32 ))
{
Printf ("write fail! \ R \ n ");
Return-1;
}
Printf ("write OK! \ R \ n ");
Close (nfp );
 
}
Close (sfp );
Return 0;
}


[Cpp]
/*************************************
File Name: client. c
Linux socket network programming example-Client Program
The server port is set to 0x8888 (the port and address can be changed according to the actual situation, or the parameter can be used for input)
Set the server address to 192.168.1.104.
Author: kikilizhm # 163.com (replace # @)
*/
 
# Include <stdlib. h>
# Include <sys/types. h>
# Include <stdio. h>
# Include <sys/socket. h>
# Include <linux/in. h>
# Include <string. h>
 
Int main ()
{
Int cfd;/* file descriptor */
Int recbytes;
Int sin_size;
Char buffer [1024] = {0};/* accept the buffer */
Struct sockaddr_in s_add, c_add;/* stores the ip address, port, and other information structures of the server and the local end */
Unsigned short portnum = 0x8888;/* The communication port used by the server, which can be changed and must be the same as that used by the server */
 
Printf ("Hello, welcome to client! \ R \ n ");
/* Establish a socket to use the Internet, TCP stream transmission */
Cfd = socket (AF_INET, SOCK_STREAM, 0 );
If (-1 = cfd)
{
Printf ("socket fail! \ R \ n ");
Return-1;
}
Printf ("socket OK! \ R \ n ");
/* Construct the ip address and port information of the server. You can query the information of the specific structure */
Bzero (& s_add, sizeof (struct sockaddr_in ));
S_add.sin_family = AF_INET;
S_add.sin_addr.s_addr = inet_addr ("192.168.1.104");/* convert the ip address to a 4-byte integer, which must be changed based on the server ip Address */
S_add.sin_port = htons (portnum);/* Here, htons converts the short Data byte sequence from the host type to the network type, which is actually
Replace the two bytes before and after the two bytes of data with the same ntohs effect and substance, except that the names are different. Htonl and ntohl are
4-byte integer of the operation. Change 0x12345678 to 0x78563412. The name is different and the content is the same in pairs. Generally, the network is a large end,
The cpu of PPC is large-end, and the cpu of x86 is small-end. arm can configure the size-end. Ensure that the byte sequence is correct during receipt.
*/
 
Printf ("s_addr =%# x, port: % # x \ r \ n", s_add.sin_addr.s_addr, s_add.sin_port);/* the output here is a small terminal.
The opposite is what we usually see. */
 
/* Connect the client to the server. The parameters are socket file descriptors, address information, and address structure size */
If (-1 = connect (cfd, (struct sockaddr *) (& s_add), sizeof (struct sockaddr )))
{
Printf ("connect fail! \ R \ n ");
Return-1;
}
Printf ("connect OK! \ R \ n ");
/* Connection successful, receiving characters from the server */
If (-1 = (recbytes = read (cfd, buffer, 1024 )))
{
Printf ("read data fail! \ R \ n ");
Return-1;
}
Printf ("read OK \ r \ nREC: \ r \ n ");
 
Buffer [recbytes] = '\ 0 ';
Printf ("% s \ r \ n", buffer );
 
Getchar ();/* indicates that the program is suspended. You can use netstat to view the current connection */
Close (cfd);/* close the connection. The communication is completed */
Return 0;
 
 
 
}


Run:


Author: kikilizhm
 


Related Article

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.