How to convert an IPv4 address into a integer in C

2019-01-01 12:37发布

I'm looking for a function that will convert a standard IPv4 address into an Integer. Bonus points available for a function that will do the opposite.

Solution should be in C#.

标签: c# integer ip ipv4
20条回答
公子世无双
2楼-- · 2019-01-01 13:09

With the UInt32 in the proper little-endian format, here are two simple conversion functions:

public uint GetIpAsUInt32(string ipString)
{
    IPAddress address = IPAddress.Parse(ipString);

    byte[] ipBytes = address.GetAddressBytes();

    Array.Reverse(ipBytes);

    return BitConverter.ToUInt32(ipBytes, 0);
}

public string GetIpAsString(uint ipVal)
{
    byte[] ipBytes = BitConverter.GetBytes(ipVal);

    Array.Reverse(ipBytes);

    return new IPAddress(ipBytes).ToString();
}
查看更多
路过你的时光
3楼-- · 2019-01-01 13:10

To convert from IPv4 to correct integer:

IPAddress address = IPAddress.Parse("255.255.255.255");
byte[] bytes = address.GetAddressBytes();
Array.Reverse(bytes); // flip big-endian(network order) to little-endian
uint intAddress = BitConverter.ToUInt32(bytes, 0);

And to convert back:

byte[] bytes = BitConverter.GetBytes(4294967295);
Array.Reverse(bytes); // flip little-endian to big-endian(network order)
string ipAddress = new IPAddress(bytes).ToString();

Explanation:

IP addresses are in network order (big-endian), while ints are little-endian on Windows, so to get a correct value, you must reverse the bytes before converting.

Also, even for IPv4, an int can't hold addresses bigger than 127.255.255.255, e.g. the broadcast address (255.255.255.255), so use a uint.

查看更多
登录 后发表回答