Linux network programs are divided into server programs and client programs. when writing network programs in linux, network communication is generally based on TCP or UDP. 1. Introduction to Concepts Network programs are divided into server programs and client programs. The server is the provider and the client is the requester. However, the actual situation is that the client and server roles of some programs are not so obvious, that is, they are mutually client and server.
When we write a network program, we usually perform network communication based on TCP or UDP.
TCP :( Transfer Control Protocol) the transmission Control Protocol is a connection-oriented Protocol. when our network programs use this Protocol, the network ensures reliable transmission between our client and the server.
UDP :( User datasync Protocol) User Datagram Protocol is a non-connection-oriented Protocol, which cannot guarantee the reliability of our network program connection.
The specific protocol used by the network program we compile depends on the specific situation. For example, if the communication requires a large amount of data and the data integrity is not very high, you can use the UDP protocol to get a faster transmission rate. If we want to implement some functions such as file transmission and social communication, we need to adopt TCP communication to ensure the reliability of transmission.
II. Introduction to Elementary network functions Nt socket (int domain, int type, int protocol)
Domain: indicates the communication clan (AF_UNIX and AF_INET) used by the host where the network program is located ).
AF_UNIX can only be used for communication between processes in a single Unix system,
AF_INET is for the Internet, so it can be remotely
Communication between hosts (when we use man socket, we find that the domain option is PF _ * instead of AF _ *. because glibc is a posix implementation, it replaces AF with PF,
But we can all use it ).
Type: communication protocol used by our network program (SOCK_STREAM, SOCK_DGRAM, etc)
SOCK_STREAM indicates that we use the TCP protocol, which provides sequential, reliable, bidirectional, and connection-oriented bit streams.
SOCK_DGRAM indicates that we use UDP protocol, which only provides fixed-length, unreliable, and connectionless communication.
Protocol: because we have specified the type, we generally only need to use 0 to replace it with socket to make basic preparations for network communication.
If the call succeeds, the file descriptor is returned. if the call fails, the value-1 is returned. you can see the error details in errno.
Int bind (int sockfd, struct sockaddr * my_addr, int addrlen)
Sockfd: The file descriptor returned by a socket call.
Addrlen: the length of the sockaddr structure.
My_addr: a pointer to sockaddr. sockaddr is defined in it.
Struct sockaddr {
Unisgned short as_family;
Char sa_data [14];
};
However, due to system compatibility, we generally do not need this header file, instead of using another structure (struct sockaddr_in). sockaddr_in is defined in it.
Struct sockaddr_in {
Unsigned short sin_family;
Unsigned short int sin_port;
Struct in_addr sin_addr;
Unsigned char sin_zero [8];
}
We mainly use the Internet, so
Sin_family is generally AF_INET,
If sin_addr is set to INADDR_ANY, it indicates that it can communicate with any host,
Sin_port is the port number we want to listen to. sin_zero [8] is used for filling.
Bind binds the local port with the file descriptor returned by the socket. 0 is returned for success, and the failure is the same as that of the socket.
Int listen (int sockfd, int backlog)
Sockfd: The file descriptor after bind.
Backlog: sets the maximum length of the request queue. when multiple client programs are connected to the server, this indicates the length of the queue that can be introduced.
The listen function changes the bind file descriptor to the listening socket. the returned information is the same as that of bind.
Int accept (int sockfd, struct sockaddr * addr, int * addrlen)
Sockfd: The file descriptor after listen.
Addr and addrlen are used to fill in the program of the client. the server only needs to pass the pointer. bind, listen and accept are functions used by the server,
When an accept is called, the server-side program will be blocked until a client program sends a connection. if accept is successful, the final server-side file descriptor will be returned,
At this time, the server can write information to this descriptor. if the descriptor fails,-1 is returned.
Int connect (int sockfd, struct sockaddr * serv_addr, int addrlen)
Sockfd: file descriptor returned by the socket.
Serv_addr: stores the connection information of the server. sin_add is the address of the server.
Addrlen: length of serv_addr
The connect function is used by the client to connect to the server. 0 is returned when the connection is successful, and-1 is returned when the file descriptor for communication with the server fails.
For more functions, see man .......
Int getaddrinfo (const char * node, const char * service,
Const struct addrinfo * hints,
Struct addrinfo ** res );
III. example of using elementary network functions A textbook-style server-side Program process is as follows:
Establish socket () ---> bind the socket to the IP address bind () -----> establish a listening socket listen () ------> Start to wait for the client to request accpet ()
The code is as follows:
Copy codeThe code is as follows:
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include
Int main (int argc, char * argv [])
{
Int sockfd, connfd;
Struct sockaddr_in srvaddr;
Struct sockaddr_in cliaddr;
Int len, port;
Char hello [] = "Hi, welcome to linux-code! \ N ";
If (sockfd = socket (AF_INET, SOCK_STREAM, 0) =-1 ){
Fprintf (stderr, "Socket error: % s \ n \ a", strerror (errno ));
Exit (1 );
}
/* Fill in the sockaddr structure on the server */
Bzero (& srvaddr, sizeof (struct sockaddr_in ));
Srvaddr. sin_family = AF_INET;
Srvaddr. sin_addr.s_addr = htonl (INADDR_ANY );
Srvaddr. sin_port = htons (1113 );
/* Bind the sockfd descriptor */
If (bind (sockfd, (struct sockaddr *) (& srvaddr), sizeof (struct sockaddr) =-1 ){
Fprintf (stderr, "Bind error: % s \ n \ a", strerror (errno ));
Exit (1 );
}
/* Listen to the sockfd descriptor */
If (listen (sockfd, 5) =-1 ){
Fprintf (stderr, "Listen error: % s \ n \ a", strerror (errno ));
Exit (1 );
}
Len = sizeof (struct sockaddr_in );
While (1) {/* server blocking until the client program establishes a connection */
If (connfd = accept (sockfd, (struct sockaddr *) (& cliaddr), & len) =-1 ){
Fprintf (stderr, "Accept error: % s \ n \ a", strerror (errno ));
Exit (1 );
}
Fprintf (stderr, "Server get connection from % s \ n", inet_ntoa (cliaddr. sin_addr ));
If (write (connfd, hello, strlen (hello) =-1 ){
Fprintf (stderr, "Write Error: % s \ n", strerror (errno ));
Exit (1 );
}
/* The communication has ended */
Close (connfd );
/* Loop next */
}
Close (sockfd );
Exit (0 );
}
A textbook client process is as follows:
Establish socket () ---> connect to the server ()
The code is as follows:
Copy codeThe code is as follows:
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include
Int main (int argc, char * argv []) {
Int sockfd; char buf [1024];
Struct sockaddr_in srvaddr;
Struct hostent * phost; int nbytes;
If (argc! = 3 ){
Fprintf (stderr, "Usage: % s \ A \ n ", argv [0]);
Exit (1 );
}
/* The customer program starts to establish the sockfd descriptor */
If (sockfd = socket (AF_INET, SOCK_STREAM, 0) =-1 ){
Fprintf (stderr, "socket Error: % s \ a \ n", strerror (errno ));
Exit (1 );
}
/* Fill in the information of the client program on the server */
Bzero (& srvaddr, sizeof (srvaddr ));
Srvaddr. sin_family = AF_INET;
Srvaddr. sin_port = htons (atoi (argv [2]);
If (inet_ton (AF_INET, argv [1], & srvaddr. sin_addr) <= 0 ){
Fprintf (stderr, "inet_ton Error: % s \ a \ n", strerror (errno ));
Exit (1 );
}
/* The client program initiates a connection request */
If (connect (sockfd, (struct sockaddr *) (& srvaddr), sizeof (struct sockaddr) =-1 ){
Fprintf (stderr, "connect Error: % s \ a \ n", strerror (errno ));
Exit (1 );
}
/* Connection successful */
If (nbytes = read (sockfd, buf, 1024) =-1 ){
Fprintf (stderr, "read Error: % s \ n", strerror (errno ));
Exit (1 );
}
Buf [nbytes] = '\ 0 ';
Printf ("received data: % s \ n", buf );
/* End communication */
Close (sockfd );
Exit (0 );
}
4. problems with the above procedures Run the server program of the above program and then run the client program. The following result is displayed:
Server result:
Viidiot @ ubuntu :~ /Code $./srv
Server get connection from 192.168.1.153
Server get connection from 127.0.0.1
Server get connection from 192.168.1.153
Client result: Viidiot @ ubuntu :~ /Code $./cli 192.168.1.153 1113
Received data: Hi, welcome to linux-code!
We have completed a simple network communication program. The I/O model used by this program is synchronous blocking ). The server calls functions such as accept () and write (). If no client is connected or the corresponding file descriptor is not ready for writing, the program will wait for nothing. In practical applications, such programs rarely appear. In practice, asynchronous I/O models are used.
If you have time, let's take a look: synchronous, asynchronous, blocking, non-blocking, select ()/poll ()/epoll ()
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