Introduction
A simple tip to retrieve IPv4 / IPv6 address from any machine.
Background
Internet Protocol version 6 (IPv6) is a mandatory part of Windows Vista and later versions. So when you ping a server greater than Windows 7, it might be responding on IPv6 or they are resolving IPv6. If they are resolving to IPv6, they might IPv6 addresses registered in DNS.
In cases when general ping commands resolve to IPv6, there might be a need for IPv4 as well as most of current manipulations require IPv4. Here is a simple trick in C# to achieve that differentiation.
Using the Code
Using System.Net
namespace following can be easily achieved.
foreach (IPAddress ipaddr in Dns.GetHostAddresses(Environment.MachineName))
{
if (ipaddr.AddressFamily ==
System.Net.Sockets.AddressFamily.InterNetwork)
{
Console.WriteLine("IP V4 Address : " + ipaddr.ToString());
}
else if (ipaddr.AddressFamily ==
System.Net.Sockets.AddressFamily.InterNetworkV6)
{
Console.WriteLine("IP V6 Address : " + ipaddr.ToString());
}
}
Code Explanation
- Get all allotted IP addresses of the machine using DNS name.
- Once we get it, parse through each IP to check its network protocol property, i.e., its
AddressFamily
- If we match IPv4 and IPv6 correspondingly assign values.
- Replace
Environment.MachineName
with any remote machine as needed. - Please refer https://msdn.microsoft.com/en-us/library/system.net.sockets.addressfamily(v=vs.110).aspx for
enum
details on AddressFamily
which determines IPv4 or IPv6.
Why this Code ??
To find the MAC address of a server, using IPv4 there are tons of ways, but with IPv6 it's complex. So this comes handy when trying to find various network properties especially for MAC
Points of Interest
I searched a lot in various websites to get IPv4 from a Windows 10 machine, which by default was returning IPv6. Hence, I am posting here so that it may be useful to others.
If you wanted to test, if machine is reachable or not at first place, please use System.Net.NetworkInformation.Ping
and System.Net.NetworkInformation.PingReply
as needed.
History
- 1st revision: 07-Dec-2015
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.