.Net IPAddress Class

This week for the .NET Framework Tour, we are going to take a brief look at the the IPAddress Class which lives in the System.Net namespace. The IPAddress class helps a developer work with IP addresses. It can parse IPv4 and IPv6 strings and returns an IPAddress object that give us helpful information. The class also helps with the manipulation of IP addresses.

To parse an IP address:

IPAddress address;

Assert.IsTrue(IPAddress.TryParse("", out address));
Assert.IsFalse(IPAddress.TryParse("", out address));

IPAddress ipv6Address = IPAddress.Parse("2001:0db8:85a3:0000:0000:8a2e:0370:7334");
Assert.AreEqual(AddressFamily.InterNetworkV6 , ipv6Address.AddressFamily);

To convert an IPv4 address to IPv6 address (and vice versa):

IPAddress ipv4Address = IPAddress.Parse("");

IPAddress ipv6Address = ipv4Address.MapToIPv6();
Assert.AreEqual(AddressFamily.InterNetworkV6, ipv6Address.AddressFamily);

More Info

The class can do a lot more than just parse strings so check out MSDN for more information about the IPAddress class. There is also a samples project on GitHub so you can play with the class to learn a bit more.

The class is schedule to come over to the open source .NET Core Libraries. See all items currently planned to move to the new open source library here.


comments powered by Disqus