Linux Network Programming

Source: Internet
Author: User
Tags rfc htons
If you want to enter the magical network programming world of Linux, please come with me. Before learning, I only need you to have a certain degree of knowledge in C language programming. The author will describe how to write a network Program Basic knowledge. The so-called network, in the opinion of software personnel, is a lot of computers connected with physical links (such as Ethernet and wireless networks) and installed with network programs. Just like a phone call, we need to know the other party's number. A network program also needs to know the computer to communicate with. Here, it is the IP address of the computer's network interface. In fact, a complete network program has two independent programs. They run on two computers, one is the network communication server, and the other is the network communication client, just like making a phone call, one phone call is required, and one phone call is the same. Therefore, we need to write two programs, which are the complete network communication program. We are familiar with Outlook, foxmail and others are client programs in network programs, while Apache and qmail are server programs. Generally, the client and server of the network program have certain communication and interaction protocols, such as SMTP, POP3, HTTP, and FTP. For the network program writers, they defined universal interaction protocols, which stipulated the work that the client and server should do. Therefore, you still need to understand the Protocol to compile the network program, we do not need to write our own protocols. There are many protocols that we can use. All of them are described in RFC documents. You can find the RFC of various protocols on the network. of course, although the first network program we are about to write is very simple, it can clearly explain the basic concepts required for most network programs, now let's take a look at the TCP server-side compiling steps of the Network Program: 1. first, you need to create a set of interfaces for communication, which are generally implemented using Socket calls. This means you have a phone number for communication :) 2. Then, you need to set a port for your interface, which is equivalent to that you have a phone number. This step is generally implemented by setting the network set interface address and calling the BIND function. 3. Call the listen function to make your set of interfaces a listening socket. The preceding three steps are common for TCP servers. 4. Call the accept function to start your socket. Then your program can wait for the connection from the client. 5. Process client connection requests. 6. Terminate the connection. Now let's take a look at the network program client programming steps: 1. The steps are the same as those on the server. 2. By setting a set of interface address structures, we describe the IP address and port of the server to which the client communicates. 3. Call the connect function to connect to the server. 4. send or receive data, which is generally implemented by calling the send and Recv functions. 5. Terminate the connection. The above steps are common. We can see that it is very interesting to write network programs, and it is not very complicated. Of course, this does not include difficult things :-), next time, I will provide a simple server and a client program. Today, what I give Code Including a server and a client program, but a lot of code is omitted, such as the error handling code. This is mainly to make the main line of network programming clear, so these two programs do not talk about network security, and stability. These are future topics. However, it is sufficient for basic understanding of network programming. Next time, I will provide a complete and runable program. Next I will explain the procedure in detail: first, we need to include some of the header files required for network programming: # include # includeint main (INT argc, char * argv []) {int listensock, connsock;/defines two socket sockets, one for listening and the other for communicating with struct sockaddr_in serveraddr;/defines the network socket address structure const char buff [] = "Hello! Welcome here! ";/Define the data buffer to be sent; listensock = socket (af_inet, sock_stream, 0);/create a socket for listening to bzero (& serveraddr, sizeof (servaddr )); /clear the serveraddr address structure. sin_family = af_inet;/Specify the communication protocol family serveraddr used. sin_addr.s_addr = htonl (inaddr_any);/specify to accept any connection because the server does not know who will ask to connect to serveraddr. sin_port = htons (5000);/Specify the listening port BIND (listensock, (sockaddr *) & serveraddr, sizeof (serveraddr);/Specify the connection address listen (listensock, 1024);/start listening to connsock = accept (Listensock, (sockaddr *) null, null);/establish a communication socket, accept function, wait for the client program to use the connect function to send (connsock, buff, sizeof (buff ), 0);/send data close (connsock) to the client;/Close the communication socket close (listensock);/Close the listening socket} This is the client program: int main (INT argc, char ** argv) {char recvbuff [100];/defines the data buffer to receive int sockfd;/defines a Socket socket for communication between struct sockaddr_in serveraddr; /define the network socket address structure if (argc! = 2) {printf ("Usage: Echo IP Address"); exit (0);} sockfd = socket (af_inet, sock_stream, 0);/create a socket bzero (& serveraddr, sizeof (serveraddr); serveraddr. sin_family = af_inet;/Specify the communication protocol family serveraddr used. sin_port = htons (5000);/Specify the port inet_ton (af_inet, argv [1], & serveraddr. sin_addr); Connect (sockfd, (sockaddr *) & serveraddr, sizeof (serveraddr);/connect to the server Recv (sockfd, recvbuff, sizeof (recvbuff), 0 ); /receive server data print F ("% s", recvbuff); // print the received data close (sockfd);/Close socket} after the two programs run, when the client connects to the server, will receive the string Hello from the server! Welcome here !, However, the task of program debugging must be completed by yourself. Do you want to know what technology OICQ uses to send and receive messages? Today, I have two programs, one server and one client program, which will tell you the basic technology. Of course, I do not mean, how is the interface made? These two programs use UDP socket programming. The last one provided is TCP socket programming. You can analyze their similarities and differences first, next time, I will analyze the differences between the two programming methods. This is the Program for sending data:/* the header file includes the required network and Basic Input and Output */# include # includeint Port = 5500; void main () {int sockfd; int COUNT = 0; int flag; char Buf [80]; struct sockaddr_in address; sockfd = socket (af_inet, sock_dgram, 0 ); // have you seen the difference? Memset (& Address, 0, sizeof (Address); Address. sin_family = af_inet; address. sin_addr.s_addr = inet_addr ("127.0.0.1"); Address. sin_port = htons (port); flag = 1; do {sprintf (BUF, "packet % d", count); If (count> 30) {sprintf (BUF, "over"); flag = 0;} sendto (sockfd, Buf, sizeof (BUF), 0, (struct sockaddr *) & Address, sizeof (Address )); // have you found that the function used is different? It also sends data count ++;} while (FLAG);} This is the program that receives data: # include # InCl Ude # include # includechar * hostname = "127.0.0.1"; // This Special IP address represents the computer's void main () {int sinlen; int Port = 8080; char message [256]; int sockfd; struct sockaddr_in sin; struct hostent * server_host_name; // The hostent structure has information such as the machine name server_host_name = gethostbyname ("127.0.0.1 "); // This function is used to obtain the host name of "127.0.0.1", that is, the local name bzero (& sin, sizeof (SIN); sin. sin_family = af_inet; sin. sin_addr.s_addr = htonl (inaddr _ Any); sin. sin_port = htons (port); sockfd = socket (pf_inet, sock_dgram, 0); // BIND (sockfd, (struct sockaddr *) & sin, sizeof (SIN); While (1) {sinlen = sizeof (SIN); recvfrom (sockfd, message, 256,0, (struct sockaddr *) & sin, & sinlen ); // It is the data-receiving function printf ("data come from server: % s", message); If (strncmp (message, "over", 4) = 0) break;} Close (sockfd);} after compilation and debugging are passed, run the receiving program in a window and the sending program in a window, you can see that the data has been created and sent. Network programs can run in two different windows on the local machine. to simulate the client and server, I will explain two important concepts in network programming: TCP programming and UDP programming are part of the splendid world of network programming that must be deeply understood. First of all, we must understand that general operating systems include windows, Linux, and Unix. The programming interfaces they provide are provided by programmers, and the names of common functions are similar. The difference is that their operating systems have different implementation details for these functions (or system calls). Therefore, when various operating systems provide network services, there are differences such as speed, efficiency, and stability. As for the selection of the set of interface words for network programming, the above differences exist. That is to say, when you select TCP socket and UDP programming, the data transmission speed, efficiency, and stability are the same. First of all, understanding this is very important to start network programming. TCP socket, the operating system provides you with a stable data path. From the programmer's point of view, you only need to understand that when you use TCP programming, if the data sending function you call, such as the send () function, returns a successful result, it indicates that the data sent by the system must be accurately received by the communication recipient. The UDP socket and the operating system provide you with an unstable, connectionless data path. So when you use UDP programming, if you call the data sending function, for example, if the sendto () function returns a success message, it indicates that the data you want to send has been sent to the Internet, and whether the data has arrived at the recipient of the data you want to send, not necessarily at that time. Therefore, for UDP programming, if we want to ensure the accuracy and timeliness of data transmission, we need to establish our own data transmission control mechanisms to ensure that our data is successfully sent to the other party, instead of simply sending data to the network, we can leave it alone. Of course, for TCP programming, the operating system has already helped us with a series of control functions, so we don't need to consider too much;-) from the above analysis, you can see that, for beginners, TCP programming is a very good entry point and is also very easy. Of course, UDP has its own advantages, but although it cannot guarantee that you send data to the other party by calling a sending function, as long as you perform proper processing, you will find that, UDP sends data faster than TCP programming! The world is not perfect! TCP programming has reliable data connections, but UDP does not. However, in terms of speed, UDP programming is better than TCP programming, especially for short message transmission. Therefore, I think OICQ is used for UDP programming, this is an important ^-^. Now I have explained the important differences between TCP and UDP programming. Although these differences are introduced by the Protocol itself, it is very good for programming. Of course, a programmer still understands how TCP programming and UDP programming are embodied in the Code. If you have carefully analyzed the two programs I mentioned earlier, you may have understood that apart from the differences between the functions used to send and receive data, the most important difference is that when you use the socket () function to create a socket, the parameter in the middle of the three parameters you need. If you want to use TCP programming, you need to use sock_stream. If you want to use UDP programming and use sock_dgram, I will introduce more in-depth Differences Between TCP and UDP later. Next time, I will tell you about the concepts and differences between servers and clients: Server/client mode is the most common mode of network communication interaction, and we must have a deep understanding of this mode. In fact, network software implements various network protocols to a large extent, whether it is official or defined by yourself. Therefore, the quality of network software is also directly related to the quality of the Protocol. Of course, the server/client mode provides such a mechanism to some extent: 1. The server-side program starts first and starts to wait. 2. The client program starts and sends a communication connection request to the server. 3. The server determines whether to accept client connection requests. In addition, give the client an answer. 4. If a connection is established between the server and the client, the common protocol will provide that party should first send data at this time, as well as the content and format of the sent data. 5. In this way, one Party sends the message, the other party accepts the message, and then replies. The communication between the server and the client is like this, but why should we choose the order of sending in sequence, possible deadlock and starvation during data transmission over the network. We can understand these two phenomena in this way. For example, I sent a message to you and waited for your answer before proceeding to the next step. However, at this time, you may also be waiting for my data to arrive, and then send an answer to me, but the problem arises. If you do not get my message (out of the package), you and I may keep waiting. Of course, common protocols, such as SMTP, POP3, FTP, and WWW, define the sequence of sending and receiving data. This is what we need to understand. The example I mentioned just now is actually a deadlock where both parties cannot continue communication. As for ELE. Me, we can think that a server can only process one user's communication request at a time. When he communicates with a client, he receives the connection request from the client, wait for the client data to be sent, but the client data is delayed (it may be lost, or the client may not send data). In this case, the server cannot communicate with other clients, all resources are used by this customer, so other client users will be starved to death. Of course, we can define many things to ensure smooth communication. For example, if one party sends a message, the other party waits. The sender repeatedly sends data multiple times before receiving an answer. The sender can also use timer and other methods to prevent starvation and deadlock. If you want to learn more methods and ideas, you can learn TCP/IP and various application protocols. They solve various possible problems at different levels. Of course, there are various obstacles on the network. The protocols you use and the code you write determine the performance and security of your network program. Therefore, network programs in real life are often very complicated.

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.