Network IP address Conversion Function in Linux

Source: Internet
Author: User

Network IP addresses are expressed in 32-bit binary format. For memory convenience, IP addresses can be expressed in dotted decimal notation. At the same time, network IP addresses are stored in different ways between network transmission and computers, the function must be used for conversion.

 

1. convert the dotted-decimal string to a long integer in decimal format: in_addr_t inet_addr (const char * CP); in_addr_t is the long type. The CP parameter indicates a dotted-decimal string, the return value is a long integer in decimal format.

 

 

2. convert a long integer IP address to a point-to-decimal char * inet_ntoa (struct in_addr In). The in parameter is an in_addr struct, which is obtained from Man 7 IP Address: struct in_addr {uint32_t s_addr}; ine_ntoa returns an IP address string in decimal format.

 

 

3. host character order and network character order conversion: The storage order of Characters in the computer and the character in the network is different. When the integer number in the computer and the integer number in the network are exchanged, related functions are required for conversion. Use the htonl function to convert a long integer IP address from a computer to an integer IP address in the network character sequence. These functions are as follows:

Uint32_t htonl (uint32_t hostlong); converts the 32-bit long integer in the computer to the 32-bit long integer in the network character sequence. (For IP address conversion)

Uint16_t htons (uint16_t hostshort); converts the number of 16-bit integers in the computer to the number of 16-bit integers in the network character sequence .. (For port conversion)

Uint32_t ntohl (uint32_t netlong); converts the 32-bit constant integer in the network to the 32-bit long integer in the computer .. (For IP address conversion)

Uint16_t ntons (uint16_t netshort); converts the number of 16-bit integers in the network to the number of 16-bit integers in the computer .. (For port conversion)

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.