C IP address and integer conversion between the specific method

  • 2020-05-19 05:40:38
  • OfStack

Conversion between an IP address and an integer

1. Convert the IP address to an integer

How it works: each segment of the IP address can be thought of as an 8-bit unsigned integer, i.e., 0-255. Divide each segment into 1 hexadecimal number and combine it into 1 unsigned 32-bit integer.

Example: one ip address is 10.0.3.193

The base 2 number corresponding to each segment
10 00001010
0 00000000
3 00000011
193 11000001
The combination is: 00001010 00000000 00000011 11000001, and the conversion to base 10 is: 167773121, which is the number converted from the IP address.

C # code:


public static long IpToInt(string ip)
        {
            char[] separator = new char[] { '.' };
            string[] items = ip.Split(separator);
            return long.Parse(items[0]) << 24
                    | long.Parse(items[1]) << 16
                    | long.Parse(items[2]) << 8 
                    | long.Parse(items[3]);
        }

2. Convert the integer to the IP address

How it works: convert this integer into a 32-bit base 2 number. From left to right, divide every 8 bits by 1 to get 4 8-bit binary digits, convert those to integers and then add ". "to the ip address.

For example, the integer :167773121

The base 2 representation is: 00001010 00000000 00000011 11000001
Divided into four sections: 1, 00001010000101, 0000001, 1110000, respectively, into an integer plus ". "after you get the 10.0.3.193.

C # code:


public static string IntToIp(long ipInt)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append((ipInt >> 24) & 0xFF).Append(".");
            sb.Append((ipInt >> 16) & 0xFF).Append(".");
            sb.Append((ipInt >> 8) & 0xFF).Append(".");
            sb.Append(ipInt & 0xFF);
            return sb.ToString();
        }


Related articles: