0

I have a v4 IP Address. I need to convert it to UInt32. In regular .NET, I was using:

string address = "192.168.1.1";
long intAddress = (long)(uint)IPAddress.NetworkToHostOrder((int)IPAddress.Parse(address).Address);

But IPAddress.Address is not available in .NET Core. What's the replacement?

user1054922
  • 1,917
  • 2
  • 20
  • 34

2 Answers2

3

Use GetAddressBytes

var intAddress = BitConverter.ToInt32(IPAddress.Parse(address).GetAddressBytes(), 0);

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

Community
  • 1
  • 1
Vlad
  • 2,340
  • 17
  • 30
  • Do I need to worry about big-endian/little-endian environment with this method? – user1054922 Nov 03 '16 at 20:30
  • 1
    I don't think so. It looks platform independent [in the source](https://github.com/dotnet/corefx/blob/93bde6d2b0cc0797ffb0dca470836ac7f86f876d/src/System.Net.Primitives/src/System/Net/IPAddress.cs#L222-L246) – Scott Chamberlain Nov 03 '16 at 20:55
  • 1
    If you're storing your value as a `UInt32`, endianness will be a potential concern no matter what operation you're using but if this value will always stay used within a .NET context then it shouldn't ever be a problem. If you're worried about it, though, it might be better to store the IP address as a byte array (or even just a string). – Abion47 Nov 03 '16 at 20:56
  • Yeah, this gives a different result from (long)(uint)IPAddress.NetworkToHostOrder((int)IPAddress.Parse(address).Address); – user1054922 Nov 03 '16 at 21:08
  • @user1054922 You've actually just given an example of endianness being a problem. Converting both this answer and the other answer into byte arrays (using "127.0.0.1" as the input), one lists `[127, 0, 0, 1]` while the other lists `[1, 0, 0, 127]`. – Abion47 Nov 04 '16 at 00:45
0
var address = IPAddress.NetworkToHostOrder((int)BitConverter.ToUInt32(IPAddress.Parse(ipAddress).GetAddressBytes(), 0));
user1054922
  • 1,917
  • 2
  • 20
  • 34