C # convert an IP address to an unsigned integer and reverse Conversion

Source: Internet
Author: User

We know that the IP address is a 32bit address assigned to each host connected to the Internet.

According to the TCP/IP protocol, IP addresses are expressed in binary format. Each IP address is 32 bits in length, and the bits are converted into four bytes.
In c #, The int32 number is four bytes, but it is not enough because the symbol occupies one place, but the unsigned UInt32 does not.

Therefore, in theory, UInt32 can be used to completely store an IP address. The following two methods are mutual conversions between IP addresses and UInt32.

 

Public static string Int2IP (UInt32 ipCode ){
Byte a = (byte) (ipCode & 0xFF000000)> 0x18 );
Byte B = (byte) (ipCode & 0x00FF0000)> 0xF );
Byte c = (byte) (ipCode & 0x0000FF00)> 0x8 );
Byte d = (byte) (ipCode & 0x000000FF );
String ipStr = String. Format ("{0}. {1}. {2}. {3}", a, B, c, d );
Return ipStr;
}

Public static UInt32 IP2Int (string ipStr ){
String [] ip = ipStr. Split (.);
Uint ipCode = 0xFFFFFF00 | byte. Parse (ip [3]);
IpCode = ipCode & 0xFFFF00FF | (uint. Parse (ip [2]) <0x8 );
IpCode = ipCode & 0xFF00FFFF | (uint. Parse (ip [1]) <0xF );
IpCode = ipCode & 0x00FFFFFF | (uint. Parse (ip [0]) <0x18 );
Return I

Related Article

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.