N
Noël Danjou
Hello,
I need to mask some bits of an IP address that I initially get as a string
so I do something like that:
IPAddress addrLo = IPAddress.Parse("172.16.0.0");
byte[] bytes = addrLo.GetAddressBytes();
Then I do some processing (mask some bits) on the "bytes" byte array and
finally I need to convert that byte array back to an IPAddress (that must
work for both IPv4 and IPv6 addresses).
For IPv6 I can use the following syntax:
addrHi = new IPAddress(bytes);
Unfortunately that does not work with IPv4 addresses (ArgumentException), so
I wrote something like that:
if (addrLo.AddressFamily == AddressFamily.InterNetworkV6)
{
// Conversion: Text(addrLo) -> Binary (addrHi)
// Only works with IPv6 addresses
addrHi = new IPAddress(bytes);
}
else
{
// Not quite efficient
// Conversion: Text(addrLo) -> Binary -> Text (addr) -> Binary (addrHi)
string addr = String.Format("{0}.{1}.{2}.{3}", bytes[0], bytes[1],
bytes[2], bytes[3]);
addrHi = IPAddress.Parse(addr);
}
Is there a better way to convert byte arrays to an IPv6/IPv4 IPAddress?
Thank you.
I need to mask some bits of an IP address that I initially get as a string
so I do something like that:
IPAddress addrLo = IPAddress.Parse("172.16.0.0");
byte[] bytes = addrLo.GetAddressBytes();
Then I do some processing (mask some bits) on the "bytes" byte array and
finally I need to convert that byte array back to an IPAddress (that must
work for both IPv4 and IPv6 addresses).
For IPv6 I can use the following syntax:
addrHi = new IPAddress(bytes);
Unfortunately that does not work with IPv4 addresses (ArgumentException), so
I wrote something like that:
if (addrLo.AddressFamily == AddressFamily.InterNetworkV6)
{
// Conversion: Text(addrLo) -> Binary (addrHi)
// Only works with IPv6 addresses
addrHi = new IPAddress(bytes);
}
else
{
// Not quite efficient
// Conversion: Text(addrLo) -> Binary -> Text (addr) -> Binary (addrHi)
string addr = String.Format("{0}.{1}.{2}.{3}", bytes[0], bytes[1],
bytes[2], bytes[3]);
addrHi = IPAddress.Parse(addr);
}
Is there a better way to convert byte arrays to an IPv6/IPv4 IPAddress?
Thank you.