Handle IP addresses in Linux network programming

Source: Internet
Author: User
Tags htons
Article title: handle IP addresses in Linux network programming. Linux is a technology channel of the IT lab in China. Includes basic categories such as desktop applications, Linux system management, kernel research, embedded systems, and open source.
Author: Cao Yuanqi
  
Linux has powerful network service capabilities, and its TCP/IP code is the highest level. Linux network implementation is similar to FreeBSD. it supports FreeBSD's extended Sockets (socket) and TCP/IP protocols. It supports the network connection between two hosts and the Sockets communication model, and implements two types of Sockets: BSD Sockets and INET Sockets. It provides two transmission protocols for different communication models and service quality, namely, unreliable, message-based UDP transmission protocol and reliable, stream-based transmission protocol TCP, it is also implemented on the IP network protocol. INET sockets is implemented based on the above two protocols and IP protocols. The relationship between them is shown in.
  
Linux network layer
  
Socket implementation in network programming
  
A socket is a basic component of network communication. It provides endpoints for two-way process communication between different hosts. Just like a phone call, a socket is like a phone call from both parties. Through Sockets programming, the program can skip the complex underlying network protocols and structures and directly compile applications unrelated to the platform. With the wide application of the Internet, Sockets has gradually become a common interface for network programming.
  
A socket exists in a specific communication domain (that is, an address family). only a socket belonging to the same address family can establish a conversation. Linux supports AF_INET (IPv4 protocol), AF_INET6 (IPv6 protocol), and AF_LOCAL (Unix domain protocol ).
  
Linux supports the following socket families or domain:
  
◆ Unix domain sockets;
  
◆ INET TneIntemet address family supports communications;
  
◆ TCP/IP protocols;
  
◆ Amateur radio X.25;
  
◆ Novel IPX;
  
◆ Appletalk DDP;
  
◆ X.25.
  
The set of interfaces is the ID of the network process. Network Communication is also a process communication. when two network processes communicate, you must first determine the network address (IP address) of each network node ). The network address can be used to determine the computer where the process is located. a computer may have multiple network processes at the same time. To distinguish different processes, Port information is also required in the socket Port. In a computer, a port can only be allocated to one process at a time. Therefore, in a computer, the port number and process can uniquely identify a network process in the entire Intemet. It can be considered that the set of interfaces = network address + port number.
  
Linux network data structure
  
There are two types of bytes in the data actually transmitted over the network: the important bytes are in the front, or the unimportant bytes are in the front. The former is called Network Byte Order (NBO). some machines store data in this Order. When a data must follow the NBO sequence, you need to call a function (such as htons () to convert it from the local Byte sequence (Host Byte Order, HBO, otherwise, the data transmitted in the past will make the other machine unreadable. This is critical for network data transmission.
  
The first structure created in the network is sockaddr. This data structure stores address information for many types of interfaces. It is defined as follows:
  
Struct sockaddr {
Unsigned short sa_family;/* This is the address family, usually in the form of AF-xxxx */
Char sa_data [14];/* 14-byte address information */
};
  
In the above code, sa_famdly is "AF_INET", indicating that it uses the Internet address family; sa_data is used to store the target address and port information for the set interface.
  
To solve struct sockaddr, a parallel structure struct sockadd_in ("in" stands for "Internet") is created, as shown below:
  
Struct sockaddr_in {
Short int sin_family;/* Address family information, usually in the form of AF-xxxx */
Unsigned short int sin_port;/* port information */
  
Struct in_addr sin_addr;/* network address */
Unsigned char sin_zero [8];/* 0 for bit complement */
}
  
The above data structure can easily process the basic elements of the set interface address. It should be explained that sin_zero is added to this structure mainly to ensure that the data length of struct sockaddr is the same as that of struct sockaddr_in, so that when using standard functions, you can use a unified data interface. Note that the bzero () function should be used to set all sin_zero to zero. Finally, sin_port and sin_addb must be Network Byte Order ). If "inadd" is declared as an example of the data structure of the secondary CT sockaddr_in, then inadd. sinadd. s_addr stores 4 bytes of IP addresses (network byte order ).
  
Another commonly used type is the unsigned type. It is more common than struct sockaddr_in or struct sockaddr described above. For the variable type unsigned, two types can be used: short (two bytes) and long (four bytes ). If you want to convert short from local bytes to network bytes, you need to use "h" to represent the local host, use "to" to represent the conversion, and then use "n" to represent the network, use "s" to represent short, which is h-to-n-s or htons () ("Host to Network Short ").
  
This conversion is required considering the scalability of different machines. We can combine the letters "n", "h", "s", and "l" to get all the conversion functions in Linux.
  
How to handle IP addresses in a Linux Network
  
Assume that you use struct sockaddr_in ina and want to store the IP address "164.112.175.124" in it, you need to call the inet_addr () function (), convert the IP address in the format of "number + period" to unsigned long. This job can be done as follows:
  
Ina. sin_addr.s_addr = inet_addr ("164.112.175.124 ");
  
The address returned by inet_addr () is already in the network byte order and does not need to be called htonl (). When an error occurs, inet_addr () returns-1. After the call, use the correct error check. for example, if the IP address is 255.255.255.255, the returned value is (unsigned)-1. Because this is a broadcast address, your program must be able to capture such errors.
  
Now you can convert the IP address in string format to 1ong. If there is a data structure struct in_addr, you must use the inet_ntoa () (ntoa stands for network to asc II) function to print it in the "number + period" format, as shown below:
  
Printf ("% s", inet_ntoa (ina. sin_addr ));
  
In this way, the IP address can be printed. Note: the parameter of the inet-ntoa () function is struct in_addr rather than long. It returns a pointer to a character.
  
The character array is stored in inet_ntoa, so it overwrites the previous content each time it calls inet_ntoa.
  
For example:
  
Char a1, * a2;
......
A1 = inet_ntoa (ina1.sin _ addr);/* assume that the address is 164.112.175.124 */
A2 = inet_ntoa (ina2.sin _ addr);/* assume that the address is 202.112.58.200 */
Printf ("address 1: % sn", a1 );
Printf ("address 2: % sn", a2 );
  
The preceding running result is:
  
Address l: 202.112.58.200
Address :202. 112.58.200
  
If you want to save the address, you can use strcpy () to save it to your character array.
  
The above describes the basic knowledge of network programming in Linux and some skills in network IP address processing. If it can be integrated with many small tools in Linux, the functions of the developed program are no less than some professional software.
  
  
  
  

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.