Question

On incoming connections via ipv4 the IPAddress is in ipv6 notation such as ::ffff:1.2.3.4

I want to compare these addresses to an IPAddress I get from elsewhere which is in ipv4 notation: 1.2.3.4

By notation I mean an ipv4.GetAddressBytes() return 4 bytes whereas ipv6.GetAddressBytes() return 16 bytes.

Is there an easy way to convert the ipv4 IPAddress to ipv6 notation?

I think I know how to do it byte by byte but I might miss something and would rather use an existing function if there is any.

Was it helpful?

Solution

Instantate your ip addresses as instances of System.Net.IPAddress. The look at the following methods:

  • IPAddress.Equals()
  • IPAddress.MapToIPv4()
  • IPAddress.MapToIPv6()

You'll probably want to add special handling for special addresses (such as the TCP/IP loopback adapter: That is a single IPv6 address, ::1, while for IPv4, even though the most commonly used address for that purpose is 127.0.0.1, the IETF has reserved the entire 127/8 block (127.0.0.0127.255.255.255 inclusive) for that purpose. How you determine equality (or even equivalency) is debatable.

Since IPv4 and IPv6 are completely different and independent addressing schemes, one might reasonably argue that the only true way of determining equivalency is if they both map to the same endpoint (MAC address/network adapter).

OTHER TIPS

Grab the IPv4 part from your "source" and compare to your "destination" IPv4, like the below sample

IPAddress ipv6 = null;
IPAddress ipv4 = null;
IPAddress testIp = null;

IPAddress.TryParse("::ffff:1.2.3.4", out ipv6);
IPAddress.TryParse("1.2.3.4", out ipv4);

string ipString = ipv6.ToString();
IPAddress.TryParse(ipString.Substring(ipString.LastIndexOf(":") + 1), out testIp);
// this will return false
Console.WriteLine("ipv4 == ipv6 : " + (ipv4.Equals(ipv6)).ToString());
// this will return true
Console.WriteLine("ipv4 == testIp : " + (ipv4.Equals(testIp)).ToString());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top