Linux Network Programming

Source: Internet
Author: User
Tags rfc


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. I will describe the basic knowledge required to write a network program.

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 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 of 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, the code I provided includes a server and a client program, but a lot of code is omitted, such as the error handling code. This is mainly used to clarify the main line of network programming, these two programs cannot 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, you must include some header files required for network programming:
# Include
# Include
# Include
# Include
Int main (int argc, char * argv [])
{
Int listensock, connsock; // defines two socket sockets, one for listening and the other for communication.
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
Bzero (& serveraddr, sizeof (servaddr);/clear the address Structure
Serveraddr. sin_family = AF_INET;/Specify the communication protocol family used
Serveraddr. sin_addr.s_addr = htonl (INADDR_ANY);/specify to accept any connection because the server does not know who will request the connection
Serveraddr. sin_port = htons (5000);/Specify the listening port
Bind (listensock, (sockaddr *) & serveraddr, sizeof (serveraddr);/specify an address for the set Interface
Listen (listensock, 1024); // start listening
Connsock = accept (listensock, (sockaddr *) NULL, NULL);/establish the communication socket, accept function, wait for the client program to connect using the connect function
Send (connsock, buff, sizeof (buff), 0); // send data to the client
Close (connsock);/close 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 be received
Int sockfd; // defines a socket for communication.
Struct sockaddr_in serveraddr;/defines 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 used
Serveraddr. sin_port = htons (5000);/Specify the port of the server to be connected
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); // receives server data
Printf ("% s
", Recvbuff); // print the received data
Close (sockfd);/close the socket
}
After the two programs run, when the client connects to the server, it will receive the string Hello! 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 does the interface work :)
The two programs use UDP socket programming. The last one is actually TCP socket programming. You can analyze their similarities and differences first. I will next time, analyze the differences between the two programming methods.
This is the data sending program:
/* The header file includes network and basic input/output */
# Include
# Include
# Include
# Include
Int 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); // do I see any 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); // do you find that the functions used are different, it also sends data
Count ++;
} While (flag );
}
This is the program that receives data:
# Include
# Include
# Include
# Include
# Include
Char * hostname = "127.0.0.1"; // This Special ip address represents the Local Computer
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 name of the local machine.
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); // This is different
Bind (sockfd, (struct sockaddr *) & sin, sizeof (sin ));
While (1 ){
Sinlen = sizeof (sin );
Recvfrom (sockfd, message, (struct sockaddr *) & sin, & sinlen); // It is a function that accepts data.
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 run the sending program in a window. Then you can see that the data is created and sent. Network programs can run in two different windows on the local machine to simulate
Today, I will explain two very important concepts in network programming: TCP programming and UDP programming. This is a part that must be deeply understood to truly enter the splendid world of network programming.

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

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.