Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

integer

ip

ipv4

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#.

like image 838
GateKiller Avatar asked Jan 20 '09 15:01

GateKiller


People also ask

How do I convert IPv4?

Pv4 to IPv6 Conversion Method1 In this method firstly to convert the Decimal IPv4 address in to Binary representation, then divide this Binary representation into four groups each group have the 8 bit binary number divide this binary number in two parts i.e 4 bits then convert this 4 bit into hexadecimal number ...

Is IP address integer or string?

IP addresses are whole numbers (the definition of integer, although they often do not meet the integer definition of some programming languages). There is one who strongly disagrees (see the comments @ stackoverflow.com/q/45067655/3745413).

Is IPv4 in decimal?

IPv4 addresses are most often written in dotted decimal notation. In this format, each 8-bit byte in the 32-bit IPv4 address is converted from binary or hexadecimal to a decimal number between 0 (0000 0000 or 0x00) and 255 (1111 1111 or 0xFF).


1 Answers

32-bit unsigned integers are IPv4 addresses. Meanwhile, the IPAddress.Address property, while deprecated, is an Int64 that returns the unsigned 32-bit value of the IPv4 address (the catch is, it's in network byte order, so you need to swap it around).

For example, my local google.com is at 64.233.187.99. That's equivalent to:

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

And indeed, http://1089059683/ works as expected (at least in Windows, tested with IE, Firefox and Chrome; doesn't work on iPhone though).

Here's a test program to show both conversions, including the network/host byte swapping:

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));     } } 
like image 163
Barry Kelly Avatar answered Sep 18 '22 12:09

Barry Kelly