views:

522

answers:

3

i have hex values in the format of 4a0e94ca etc, and i need to convert them into IP's, how can i do this in C# ?

+3  A: 

Well, take the format of an IP in this form:

192.168.1.1

To get it into a single number, you take each part, OR it together, while shifting it to the left, 8 bits.

long l = 192 | (168 << 8) | (1 << 16) | (1 << 24);

Thus, you can reverse this process for your number.

Like so:

int b1 = (int) (l & 0xff);
int b2 = (int) ((l >> 8) & 0xff);
int b3 = (int) ((l >> 16) & 0xff);
int b4 = (int) ((l >> 24) & 0xff);

-- Edit

Other posters probably have 'cleaner' ways of doing it in C#, so probably use that in production code, but I do think the way I've posted is a nice way to learn the format of IPs.

Noon Silk
+1 - I believe knowing the bitwise math is probably the most important part of converting integers to IPs (and vice versa), even if your language does it for you.
Matthew Iselin
@Matthew: While I agree knowing Bitwise math is useful, most languages that are C derived have the function inet_ntop and inet_pton for exactly this purpose.
R. Bemrose
@R. Bemrose: Sure, but I think it's good to know how those functions *work*. Each to his own though, some people aren't as excited as I am about what's happening at the lower levels :)
Matthew Iselin
+2  A: 

Check http://stackoverflow.com/questions/1139957/c-convert-int-to-hex-and-back-again

    var ip = String.Format("{0}.{1}.{2}.{3}",
    int.Parse(hexValue.Substring(0, 2), System.Globalization.NumberStyles.HexNumber),
    int.Parse(hexValue.Substring(2, 2), System.Globalization.NumberStyles.HexNumber),
    int.Parse(hexValue.Substring(4, 2), System.Globalization.NumberStyles.HexNumber),
    int.Parse(hexValue.Substring(6, 2), System.Globalization.NumberStyles.HexNumber));
Yannick M.
That is a pretty decent way, but maybe not the fastest. Still, +1.
John Gietzen
+12  A: 

If the values represent IPv4 addresses you can use the long.Parse method and pass the result to the IPAddress constructor:

var ip = new IPAddress(long.Parse("4a0e94ca", NumberStyles.AllowHexSpecifier));

If they represent IPv6 addresses you should convert the hex value to a byte array and then use this IPAddress constructor overload to construct the IPAddress.

dtb
Also very good. +1
John Gietzen
Cleaner than my method :)
Noon Silk
Seems like the best way to me
Yannick M.
Note - "var" will only work in .Net framework 3.5 or higher.
DmitryK