How to convert an IPv4 address to an integer in C #?

I am looking for a function that converts a standard IPv4 address to Integer. Bonus points are available for a function that will do the opposite.

The solution should be in C #.

+95
c # integer ip ipv4
Jan 20 '09 at 15:25
source share
22 answers
// IPv4 int intAddress = BitConverter.ToInt32(IPAddress.Parse(address).GetAddressBytes(), 0); string ipAddress = new IPAddress(BitConverter.GetBytes(intAddress)).ToString(); 

EDIT: As noted in other answers, when you run this fragment on a small destination machine, it will issue bytes in the reverse order, as defined by the standard. However, the question requires a comparison between an integer and an IP address, not a conversion to a standard integer format. To do this, you need to consider the final version of the machine on which you work.

+134
Jan 20 '09 at 15:30
source share

Unsigned 32-bit integers are IPv4 addresses. Meanwhile, the IPAddress.Address property, while deprecated, is Int64, which returns a 32-bit unsigned IPv4 address (catch, this is in network byte order, so you need to change it).

For example, my local google.com is located at 64.233.187.99 . This is equivalent to:

 64*2^24 + 233*2^16 + 187*2^8 + 99 = 1089059683 

And indeed http: // 1089059683 / works as expected (at least on Windows, tested with IE, Firefox and Chrome, but not working on iPhone).

Here is a test program for displaying both conversions, including network / host byte exchange:

 using System; using System.Net; class App { static long ToInt(string addr) { // careful of sign extension: convert to uint first; // unsigned NetworkToHostOrder ought to be provided. return (long) (uint) IPAddress.NetworkToHostOrder( (int) IPAddress.Parse(addr).Address); } static string ToAddr(long address) { return IPAddress.Parse(address.ToString()).ToString(); // This also works: // return new IPAddress((uint) IPAddress.HostToNetworkOrder( // (int) address)).ToString(); } static void Main() { Console.WriteLine(ToInt("64.233.187.99")); Console.WriteLine(ToAddr(1089059683)); } } 
+135
Jan 20 '09 at 15:30
source share

@Barry Kelly and @Andrew Hare, in fact, I do not think that multiplication is the clearest way to do this (everything is correct).

Int32 "formatted" IP address can be considered as the following structure

 [StructLayout(LayoutKind.Sequential, Pack = 1)] struct IPv4Address { public Byte A; public Byte B; public Byte C; public Byte D; } // to actually cast it from or to an int32 I think you // need to reverse the fields due to little endian 

So, to convert the IP address 64.233.187.99, you can do:

 (64 = 0x40) << 24 == 0x40000000 (233 = 0xE9) << 16 == 0x00E90000 (187 = 0xBB) << 8 == 0x0000BB00 (99 = 0x63) == 0x00000063 ---------- =| 0x40E9BB63 

so you can add them with + or you could use binairy or together. The result is in 0x40E9BB63, which is 1089059683. (In my opinion, looking in hexadecimal is much easier to see bytes)

So you can write a function as:

 int ipToInt(int first, int second, int third, int fourth) { return (first << 24) | (second << 16) | (third << 8) | (fourth); } 
+38
Jan 21 '09 at 8:41
source share

Here are a couple of methods for converting from IPv4 to the correct integer and vice versa:

 public static uint ConvertFromIpAddressToInteger(string ipAddress) { var address = IPAddress.Parse(ipAddress); byte[] bytes = address.GetAddressBytes(); // flip big-endian(network order) to little-endian if (BitConverter.IsLittleEndian) { Array.Reverse(bytes); } return BitConverter.ToUInt32(bytes, 0); } public static string ConvertFromIntegerToIpAddress(uint ipAddress) { byte[] bytes = BitConverter.GetBytes(ipAddress); // flip little-endian to big-endian(network order) if (BitConverter.IsLittleEndian) { Array.Reverse(bytes); } return new IPAddress(bytes).ToString(); } 

example

 ConvertFromIpAddressToInteger("255.255.255.254"); // 4294967294 ConvertFromIntegerToIpAddress(4294967294); // 255.255.255.254 

explanation

IP addresses are in network order (with direct byte order), while int on Windows have lower byte order, so to get the right value, you must reverse the bytes in order before converting to a system with direct byte order.

Also, even for IPv4 , int cannot contain addresses greater than 127.255.255.255 , such as a broadcast address (255.255.255.255) , so use uint .

+31
Nov 12
source share

Try the following:

 private int IpToInt32(string ipAddress) { return BitConverter.ToInt32(IPAddress.Parse(ipAddress).GetAddressBytes().Reverse().ToArray(), 0); } private string Int32ToIp(int ipAddress) { return new IPAddress(BitConverter.GetBytes(ipAddress).Reverse().ToArray()).ToString(); } 
+12
May 28 '09 at 2:55 p.m.
source share

Since no one has sent code that uses BitConverter and actually checks for compliance, here goes:

 byte[] ip = address.Split('.').Select(s => Byte.Parse(s)).ToArray(); if (BitConverter.IsLittleEndian) { Array.Reverse(ip); } int num = BitConverter.ToInt32(ip, 0); 

and back:

 byte[] ip = BitConverter.GetBytes(num); if (BitConverter.IsLittleEndian) { Array.Reverse(ip); } string address = String.Join(".", ip.Select(n => n.ToString())); 
+7
Nov 01 '13 at 13:52
source share

I ran into some problems with the solutions described, having run into IP addresses with a very large value. The result would be that byte [0] * 16777216 thingy would overflow and become a negative int value. what fixed for me is a simple type casting operation.

 public static long ConvertIPToLong(string ipAddress) { System.Net.IPAddress ip; if (System.Net.IPAddress.TryParse(ipAddress, out ip)) { byte[] bytes = ip.GetAddressBytes(); return (long) ( 16777216 * (long)bytes[0] + 65536 * (long)bytes[1] + 256 * (long)bytes[2] + (long)bytes[3] ) ; } else return 0; } 
+6
Nov 08 2018-10-1120:
source share

Davy Landman Inverse Function

 string IntToIp(int d) { int v1 = d & 0xff; int v2 = (d >> 8) & 0xff; int v3 = (d >> 16) & 0xff; int v4 = (d >> 24); return v4 + "." + v3 + "." + v2 + "." + v1; } 
+4
Dec 21 '13 at 18:46
source share

My question was closed, I have no idea why. The answer here is not what I need.

This gives me the correct integer value for IP ..

 public double IPAddressToNumber(string IPaddress) { int i; string [] arrDec; double num = 0; if (IPaddress == "") { return 0; } else { arrDec = IPaddress.Split('.'); for(i = arrDec.Length - 1; i >= 0 ; i = i -1) { num += ((int.Parse(arrDec[i])%256) * Math.Pow(256 ,(3 - i ))); } return num; } } 
+3
Jan 22 '09 at 9:18
source share

Collected several of the answers above into an extension method that processes the Endianness of the machine and processes the IPv4 addresses that have been mapped to IPv6.

 public static class IPAddressExtensions { /// <summary> /// Converts IPv4 and IPv4 mapped to IPv6 addresses to an unsigned integer. /// </summary> /// <param name="address">The address to conver</param> /// <returns>An unsigned integer that represents an IPv4 address.</returns> public static uint ToUint(this IPAddress address) { if (address.AddressFamily == AddressFamily.InterNetwork || address.IsIPv4MappedToIPv6) { var bytes = address.GetAddressBytes(); if (BitConverter.IsLittleEndian) Array.Reverse(bytes); return BitConverter.ToUInt32(bytes, 0); } throw new ArgumentOutOfRangeException("address", "Address must be IPv4 or IPv4 mapped to IPv6"); } } 

Unit tests:

 [TestClass] public class IPAddressExtensionsTests { [TestMethod] public void SimpleIp1() { var ip = IPAddress.Parse("0.0.0.15"); uint expected = GetExpected(0, 0, 0, 15); Assert.AreEqual(expected, ip.ToUint()); } [TestMethod] public void SimpleIp2() { var ip = IPAddress.Parse("0.0.1.15"); uint expected = GetExpected(0, 0, 1, 15); Assert.AreEqual(expected, ip.ToUint()); } [TestMethod] public void SimpleIpSix1() { var ip = IPAddress.Parse("0.0.0.15").MapToIPv6(); uint expected = GetExpected(0, 0, 0, 15); Assert.AreEqual(expected, ip.ToUint()); } [TestMethod] public void SimpleIpSix2() { var ip = IPAddress.Parse("0.0.1.15").MapToIPv6(); uint expected = GetExpected(0, 0, 1, 15); Assert.AreEqual(expected, ip.ToUint()); } [TestMethod] public void HighBits() { var ip = IPAddress.Parse("200.12.1.15").MapToIPv6(); uint expected = GetExpected(200, 12, 1, 15); Assert.AreEqual(expected, ip.ToUint()); } uint GetExpected(uint a, uint b, uint c, uint d) { return (a * 256u * 256u * 256u) + (b * 256u * 256u) + (c * 256u) + (d); } } 
+2
May 31 '15 at 18:34
source share

If you are interested in a function, not only the answer here is how it is done:

 int ipToInt(int first, int second, int third, int fourth) { return Convert.ToInt32((first * Math.Pow(256, 3)) + (second * Math.Pow(256, 2)) + (third * 256) + fourth); } 

with first through fourth are IPv4 address segments.

+1
Jan 20 '09 at 15:36
source share

With UInt32 in the correct 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(); } 
+1
Jan 17 '13 at 21:01
source share
 public bool TryParseIPv4Address(string value, out uint result) { IPAddress ipAddress; if (!IPAddress.TryParse(value, out ipAddress) || (ipAddress.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork)) { result = 0; return false; } result = BitConverter.ToUInt32(ipAddress.GetAddressBytes().Reverse().ToArray(), 0); return true; } 
+1
May 29 '13 at 20:58
source share
  public static Int32 getLongIPAddress(string ipAddress) { return IPAddress.NetworkToHostOrder(BitConverter.ToInt32(IPAddress.Parse(ipAddress).GetAddressBytes(), 0)); } 

The above example will be what I will be. The only thing you may need to do is convert to UInt32 for display purposes or entire strings, including using it as a long address in string form.

This is what you need when using the IPAddress.Parse (String) function. Sigh.

+1
Apr 16 '14 at 10:01
source share

here is the solution i developed today (should have been googled first!):

  private static string IpToDecimal2(string ipAddress) { // need a shift counter int shift = 3; // loop through the octets and compute the decimal version var octets = ipAddress.Split('.').Select(p => long.Parse(p)); return octets.Aggregate(0L, (total, octet) => (total + (octet << (shift-- * 8)))).ToString(); } 

I use LINQ, lambda and some extensions in generics, so while it produces the same result, it uses some new language features, and you can do this in three lines of code.

I have an explanation on my blog if you are interested.

amuses, -jc

0
May 05 '09 at 9:59 p.m.
source share

I think this is wrong: "65536" ==> 0.0.255.255 "Should be:" 65535 "==> 0.0.255.255" or "65536" ==> 0.1.0.0 "

0
Jun 05 '09 at 23:18
source share

@Davy Ladman your shift decision is corrent, but only for ip starting with a number less than or equal to 99, the infact first octect should be discarded to the end.

In any case, converting back with a long type is quite difficult, because the storage is 64 bits (not 32 for Ip) and fills 4 bytes with zeros

 static uint ToInt(string addr) { return BitConverter.ToUInt32(IPAddress.Parse(addr).GetAddressBytes(), 0); } static string ToAddr(uint address) { return new IPAddress(address).ToString(); } 

Enjoy it!

Massimo

0
Mar 16 '11 at 16:50
source share

Assuming you have an IP address in a string format (e.g. 254.254.254.254)

 string[] vals = inVal.Split('.'); uint output = 0; for (byte i = 0; i < vals.Length; i++) output += (uint)(byte.Parse(vals[i]) << 8 * (vals.GetUpperBound(0) - i)); 
0
Jun 06 '14 at 1:16
source share
 var ipAddress = "10.101.5.56"; var longAddress = long.Parse(string.Join("", ipAddress.Split('.').Select(x => x.PadLeft(3, '0')))); Console.WriteLine(longAddress); 

Output: 10101005056

0
Aug 26
source share
 var address = IPAddress.Parse("10.0.11.174").GetAddressBytes(); long m_Address = ((address[3] << 24 | address[2] << 16 | address[1] << 8 | address[0]) & 0x0FFFFFFFF); 
0
Mar 16 '16 at 4:01
source share

I noticed that System.Net.IPAddress has an Address property (System.Int64) and a constructor that also accepts an Int64 data type. Thus, you can use this to convert an IP address to / from a numeric (although not Int32, but Int64) format.

0
Feb 15 '19 at 9:08
source share

Take a look at some of the craziest parsing examples in .Net IPAddress.Parse: ( MSDN )

"65536" ==> 0.0.255.255
"20.2" ==> 20.0.0.2
"20.65535" ==> 20.0.255.255
"128.1.2" ==> 128.1.0.2

-one
Jan 22 '09 at 8:32
source share



All Articles