Network Programming in Linux
Xuyb
Email: bai_xy@21cn.com
This article introduces common socket programming functions in Linux, General socket programming rules, precautions for programming of customer/Server models, and solutions to common problems, and a specific code generation instance. To understand the technical issues discussed in this article, you must have some C programming experience and basic knowledge about TCP/IP. The example in this article requires the GCC compilation platform support in Linux.
Socket Definition
Network socket data transmission is a special type of I/O, and socket is also a file descriptor. Socket also has a function call similar to opening a file-socket (). This function returns an integer socket descriptor, and subsequent connection establishment and data transmission operations are implemented through this socket. There are two common socket types: stream Socket-SOCK_STREAM and datagram Socket-SOCK_DGRAM. Streaming is a connection-oriented socket for connection-oriented TCP Service applications; datagram socket is a connectionless socket that corresponds to connectionless UDP Service applications.
Definition of data types related to socket programming
There are two types of computer data storage priorities: high byte priority and low byte priority. Data on intenet is transmitted over the network in high byte priority. Therefore, for machines that store data in low byte priority mode, data needs to be converted when transmitted over the Internet.
The first structure type we will discuss is struct sockaddr, which is used to save socket information:
Struct sockaddr {
Unsigned short sa_family;/* address family, af_xxx */
Char sa_data [14];/* 14-byte Protocol address */};
Sa_family is generally af_inet; sa_data contains the IP address and port number of the socket.
There is also a structure type:
Struct sockaddr_in {
Short int sin_family;/* address family */
Unsigned short int sin_port;/* Port Number */
Struct in_addr sin_addr;/* IP Address */
Unsigned char sin_zero [8];/* fill in 0 to maintain the same size as struct sockaddr
Small */
};
This structure is more convenient to use. Sin_zero (which is used to fill the sockaddr_in structure with the same length as struct sockaddr) should be set to zero using the bzero () or memset () function. The pointer to sockaddr_in and the pointer to sockaddr can be converted to each other, which means that if the parameter type required by a function is sockaddr, you can convert a pointer to sockaddr_in to a pointer to sockaddr when calling a function; or vice versa. Sin_family is usually assigned af_inet; in_port and sin_addr should be converted into network byte precedence, while sin_addr does not need to be converted.
We will discuss several bytes sequence conversion functions below:
Htons () -- "host to network short"; htonl () -- "host to network long"
Ntohs () -- "network to host short"; ntohl () -- "network to host long"
Here, h indicates "host", N indicates "network", s indicates "short", and l indicates "long"
.
Open socket descriptor, establish binding, and establish connection
The socket function is prototype:
Int socket (INT domain, int type, int Protocol );
The domain parameter specifies the socket type: sock_stream or sock_dgram; Protocol is usually assigned "0 ". The socket () call returns an integer socket descriptor, which you can use later. Once a socket descriptor is returned through a socket call, you should associate the socket with a port on your local machine (this function is often called when you design a server program. Then you can listen for service requests on this port, and the client generally does not need to call this function ). The BIND function is prototype:
Int BIND (INT sockfd, struct sockaddr * my_addr, int addrlen );
Sockfd is a socket descriptor. my_addr is a sockaddr pointer that points to information such as the local IP address and port number. addrlen is often set to sizeof (struct sockaddr ).
Finally, for the BIND function, you can use the following value assignment to automatically obtain the local IP address and randomly obtain an unused port number:
My_addr.sin_port = 0;/* The system randomly selects an unused Port Number */
My_addr.sin_addr.s_addr = inaddr_any;/* enter the local IP Address */
By setting my_addr.sin_port to 0, the function automatically selects an unused port for you to use. Similarly, by setting my_addr.sin_addr.s_addr to inaddr_any, the system automatically fills in the local IP address. When the BIND () function is successfully called, 0 is returned. When an error is encountered, "-1" is returned and errno is set to the corresponding error number. In addition, when calling a function, do not set the port number to a value smaller than 1024, because 1 ~ 1024 is the reserved port number. You can use any unused port number greater than 1024.
The CONNECT () function is used to establish a TCP connection with the remote server. Its prototype is:
Int connect (INT sockfd, struct sockaddr * serv_addr, int addrlen );
Sockfd is the sockt descriptor of the target server; serv_addr is a pointer containing the IP address and port number of the target server. -1 is returned when an error occurs, and errno contains the corresponding error code. For client program design, you do not need to call BIND (), because in this case, you only need to know the IP address of the target machine, and you do not need to care about which port the customer uses to establish a connection with the server, the kernel automatically selects an unused port for the client to use.
Listen () -- listen for service requests
In a server program, when a socket is bound with a port, you need to listen to the port to process the incoming service requests.
Int listen (INT sockfd, int backlog );
Sockfd is the socket descriptor returned by the Socket System Call. Backlog specifies the maximum number of requests allowed in the Request queue. incoming connection requests will wait for accept () in the queue (refer to below ). Cklog limits the number of requests waiting for service in the queue. The default value is 20 for most systems.
When the listen encounters an error,-1 is returned, and errno is set to the corresponding error code.
Therefore, server programs generally call functions in the following order:
Socket (); BIND (); Listen ();/* accept () goes here */
Accept () -- connection port service request.
When a client tries to connect to the port listened by the server, the connection request will wait in queue for the server accept. Call the accept () function to establish a connection for it. The accept () function returns a new socket descriptor for this new connection. The server can continue to listen on the previous socket and send and Recv () (receive) data on the new socket descriptor:
Int accept (INT sockfd, void * ADDR, int * addrlen );
Sockfd is the socket descriptor to be monitored. ADDR is usually a pointer to the sockaddr_in variable, this variable is used to store the information of the host requesting the service (a host sends this request from a port); addrten is usually a point value of sizeof (struct sockaddr_in). When an error occurs, a-1 value is returned and the corresponding errno value is set.
Send () and Recv () -- Data Transmission
These two functions are used for data transmission on the connected socket.
The send () function is prototype:
Int send (INT sockfd, const void * MSG, int Len, int flags );
Sockfd is the socket descriptor you want to use to transmit data, and MSG is a pointer to the data to be sent.
Len is the length of data in bytes. Flags is usually set to 0 (for the usage of this parameter, refer to the man Manual ).
Char * MSG = "beej was here! "; Int Len, bytes_sent ;......
Len = strlen (MSG); bytes_sent = Send (sockfd, MSG, Len, 0 );......
The send () function returns the number of actually sent bytes, which may be less than the data you want to send. Therefore, the return value of send () needs to be measured. When the return value of send () does not match Len, this situation should be processed.
The Recv () function is prototype:
Int Recv (INT sockfd, void * Buf, int Len, unsigned int flags );
Sockfd is the socket descriptor for receiving data, Buf is the buffer for storing received data, and Len is the buffer length. Flags is also set to 0. Recv () returns the number of actually received bytes, or if an error occurs,-1 is returned and the corresponding errno value is set.
Sendto () and recvfrom () -- Data Transmission Using Datagram
In the connectionless datagram socket mode, because the local socket does not establish a connection with the remote machine, the destination address should be specified when sending data. The prototype of the sendto () function is:
Int sendto (INT sockfd, const void * MSG, int Len, unsigned int flags, const struct sockaddr * To, int tolen );
This function has two more parameters than the send () function. To indicates the IP address and port number of the host, while tolen is often assigned sizeof (struct sockaddr ). The sendto function also returns the actual length of data bytes or-1 in case of a sending error.
The original recvfrom () function is:
Int recvfrom (INT sockfd, void * Buf, int Len, unsigned int lags, struct sockaddr * From, int * fromlen );
From is a variable of the struct sockaddr type, which saves the IP address and port number of the source machine. Fromlen is often set to sizeof (struct sockaddr ). When recvfrom () is returned, fromlen contains the number of data bytes actually stored in from. The recvfrom () function returns the number of bytes received or-1 if an error occurs, and the corresponding errno is set.
It should be noted that when you call the connect () function for the datagram socket, you can also use send () and Recv () for data transmission, however, this socket is still a datagram socket and uses the UDP Service at the transport layer. However, when sending or receiving data reports, the kernel automatically adds the object and source address information.
Close () and Shutdown () -- end Data Transmission
After all data operations are completed, you can call the close () function to release the socket.
Stop any data operations on the socket: Close (sockfd );
You can also call the shutdown () function to close the socket. This function allows you to stop data transmission in a certain direction, while data transmission in one direction continues. For example, you can close the write operation of a socket and allow the socket to continue to accept data until all data is read.
Int Shutdown (INT sockfd, int how );
The meaning of sockfd is obvious, and the parameter How can be set to the following values:
· 0 ------- you are not allowed to continue receiving data.
· 1 ------- data cannot be sent again
· 2 ------- no data can be sent or received. If both are allowed, close () is called ()
If the shutdown operation succeeds, 0 is returned. If an error occurs,-1 is returned (and the corresponding errno is set ).
DNS-Domain Name Service Functions
Because IP addresses are hard to remember and read/write, in order to facilitate read/write memory, people often use domain names to represent hosts, which requires domain name and IP address conversion. The gethostbyname () function completes this conversion. The function prototype is:
Struct hostent * gethostbyname (const char * Name );
The function returns a schema type named hosten, which is defined as follows:
Struct hostent {
Char * h_name;/* Host's official domain name */
Char ** h_aliases;/* an array of host aliases ending with null */
Int h_addrtype;/* return address type, in the Internet environment is AF-INET */
Int h_length;/* the length of the address in bytes */
Char ** h_addr_list;/* an array ending with 0, containing all addresses of the Host */
};
# Define h_addr h_addr_list [0]/* The first address in H-ADDR-list */
When gethostname () is called successfully, a pointer to struct hosten is returned. If the call fails,-1 is returned. When gethostbyname is called, you cannot use the perror () function to output error information. Instead, use the herror () function to output error information.
Connection-oriented client/server code instances
This server sends the string "Hello, world!" to the customer through a connection! ". If you run the software on the server and the client runs the software on the client, the client receives the string.
For the software code of this server, see program 1:
# Include stdio. h
# Include stdlib. h
# Include errno. h
# Include string. h
# Include sys/types. h
# Include netinet/in. h
# Include sys/socket. h
# Include sys/Wait. H
# Define myport 3490/* server listening port number */
# Define backlog 10/* Maximum number of simultaneous connection requests */
Main ()
{
Intsock FD, new_fd;/* listen to socket: sock_fd, data transmission socket: new_fd */
Struct sockaddr_in my_addr;/* local address information */
Struct sockaddr_in their_addr;/* customer address information */
Int sin_size;
If (sockfd = socket (af_inet, sock_stream, 0) =-1) {/* error detection */
Perror ("socket"); exit (1 );}
My_addr.sin_family = af_inet;
My_addr.sin_port = htons (myport );
My_addr.sin_addr.s_addr = inaddr_any;
Bzero (& (my_addr.sin_zero), 8 );
If (BIND (sockfd, (struct sockaddr *) & my_addr, sizeof (struct sockaddr ))
=-1) {/* error detection */
Perror ("bind"); exit (1 );}
If (Listen (sockfd, backlog) =-1) {/* error detection */
Perror ("listen"); exit (1 );}
While (1) {/* main accept () loop */
Sin_size = sizeof (struct sockaddr_in );
If (new_fd = accept (sockfd, (struct sockaddr *) & their_addr,
& Sin_size) =-1 ){
Perror ("accept"); continue ;}
Printf ("server: Got connection from % s", inet_ntoa (their_addr.sin_addr ));
If (! Fork () {/* child process code segment */
If (send (new_fd, "Hello, world! ", 14, 0) =-1)
Perror ("send"); close (new_fd); exit (0 );}
Close (new_fd);/* the socket is no longer required by the parent process */
Waitpid (-1, null, wnohang)> 0/* wait until the child process ends and clear the resources occupied by the child process */
}
}
(Procedure 1)
The server first creates a socket and then binds the socket to the local address/port number. After the socket is successfully created, it listens to the corresponding socket. When accpet captures a connection service request, generate a new socket and send the string "Hello, world!" to the client through the new socket! ", And then close the socket.
The fork () function generates a sub-process to process the data transmission part. The value returned by the fork () Statement for the sub-process is 0. Therefore, the IF statement containing the fork function is the sub-process code part, and it is executed concurrently with the parent Process Code part after the if statement.
For the client software code, see Program 2:
# Define destdio. h
# Include stdlib. h
# Include errno. h
# Include string. h
# Include netdb. h
# Include sys/types. h
# Include netinet/in. h
# Include sys/socket. h
# Define Port 3490
# Define maxdatasize 100/* maximum data transmission volume each time */
Int main (INT argc, char * argv [])
{
Int sockfd, numbytes;
Char Buf [maxdatasize];
Struct hostent * He;
Struct sockaddr_in their_addr;
If (argc! = 2 ){
Fprintf (stderr, "Usage: client hostname"); exit (1 );}
If (He = gethostbyname (argv [1]) = NULL ){
Herror ("gethostbyname"); exit (1 );}
If (sockfd = socket (af_inet, sock_stream, 0) =-1 ){
Perror ("socket"); exit (1 );}
Their_addr.sin_family = af_inet;
Their_addr.sin_port = htons (port );
Their_addr.sin_addr = * (struct in_addr *) He-> h_addr );
Bzero (& (their_addr.sin_zero), 8 );
If (connect (sockfd, (struct sockaddr *) & their_addr,
Sizeof (struct sockaddr) =-1) {/* error detection */
Perror ("Connect"); exit (1 );}
If (numbytes = Recv (sockfd, Buf, maxdatasize, 0) =-1 ){
Perror ("Recv"); exit (1 );}
Buf [numbytes] = '';
Printf ("Received: % s", Buf );
Close (sockfd );
Return 0;
}
(Procedure 2)
The client code is relatively simple. First, obtain the IP address of the server domain name, create a socket, call the connect function to establish a connection with the server, and then receive the data sent from the server after the connection is successful, close the socket and end the program.
The principle of a connectionless client/server program is the same as that of a connected Client/Server. The difference between the two is that customers in a connectionless Client/Server generally do not need to establish a connection, when sending and receiving data, you must specify the address of the remote machine.
Regarding the concept of blocking and the select () function, what happens when the server runs an accept statement without a client connection request? In this case, the server stops waiting for the connection service request on the accept statement. Similarly, when the program runs to receive the data statement, if no data can be read, the program will also stop on the receiving statement. This is called blocking. However, if you want the server to check whether a client is waiting for a connection, accept the connection. Otherwise, you can set socke to non-blocking: the non-blocking Socket enables the Accept call to return immediately when no client is waiting.
# Include unistd. h
# Include fcntl. h
...; Sockfd = socket (af_inet, sock_stream, 0 );
Fcntl (sockfd, f_setfl, o_nonblock );.....
By setting the socket as a non-blocking method, you can implement "polling" Several sockets. When an attempt is made to read data from a non-blocking socket without data waiting for processing, the function will return immediately, and the return value is set to-1, and errno is set to ewouldblock. However, this "Round Robin" will make the CPU in a busy waiting mode, thus reducing performance. Considering this situation, if you want the server to listen to Connection Service requests and read data from established connections, you may think of using one accept statement and multiple Recv () statements, however, since both accept and Recv are blocked, this idea is obviously not successful.
Calling a non-blocking socket will greatly waste system resources. The call to select () can effectively solve this problem. It allows you to hook the process itself and enable the system kernel to listen to any activity of a set of file descriptors required by the system kernel, as long as the activity is confirmed on any monitored file descriptor, the Select () call will return information indicating that the file descriptor is prepared, so as to select random changes for the process, the CPU overhead does not need to be wasted because the process itself tests the input. The prototype of the select function is:
Int select (INT numfds, fd_set * readfds, fd_set * writefds, fd_set * exeptfds, struct timeval * timeout );
Readfds, writefds, and limit TFDs are the collection of read, write, and exception handling file descriptors monitored by select. If you want to determine whether data can be read from the standard input and a socket descriptor, you only need to add the file descriptor 0 and the corresponding sockdtfd of the standard input to the readfds set; the numfds value is the file descriptor with the highest number to be checked plus 1. In this example, the numfds value should be sockfd + 1. When the SELECT statement is returned, readfds will be modified, indicates that a file descriptor has been read. You can test it through fd_issset. To set, reset, and test the file descriptor corresponding to fd_set, it provides a set of macros:
Fd_zero (fd_set * Set) ---- clears a file descriptor set;
Fd_set (int fd, fd_set * Set) ---- Add a file descriptor to the file descriptor set;
Fd_clr (int fd, fd_set * Set) ---- clears a file descriptor from the file descriptor set
;
Fd_isset (int fd, fd_set * Set) ---- try to determine whether the file descriptor is set.
The timeout parameter is a pointer to the struct timeval type, which enables select () to return if no file descriptor is ready after waiting for a long time. Struct timeval data structure:
Struct timeval {
Int TV _sec;/* seconds */
Int TV _usec;/* microseconds */
};
We will explain through Program 3:
# Include sys/time. h
# Include sys/types. h
# Include unistd. h
# Define stdin 0/* standard input file descriptor */
Main ()
{
Struct timeval TV;
Fd_set readfds;
TV. TV _sec = 2;
TV. TV _usec = 500000;
Fd_zero (& readfds );
Fd_set (stdin, & readfds );
/* The collection of file descriptors for writing and exception handling is not concerned here */
Select (stdin + 1, & readfds, null, null, & TV );
If (fd_isset (stdin, & readfds) printf ("A key was pressed! ");
Else printf ("timed out .");
}
(Procedure 3)
Select () is returned from select after the monitored port waits for 2.5 seconds