Some OS like Windows XP or Windows 2003 have choice to turn on V6 format IP address.
Some times we need to find V4 format IP address. How to do it?
There are two ways for it. First you can pass empty or null string to GetHostAddresses of Dns class or other way is to comapre AddressFamily of addresses returned by function.
I am giving code in C# using .Net 2.0 to find V4 format IP address.
# method 1
string GetV4IPAddress()
{
IPAddress[] ips;
string hostname = "";
// getting all IP addresses
ips = Dns.GetHostAddresses(hostname);
// now print them
foreach (IPAddress ip in ips)
{
Console.Writeline("IP: {0}", ip);
}
}
# method 2
string GetV4IPAddress()
{
IPAddress[] ips;
string hostname = "";
// getting all IP addresses
ips = Dns.GetHostAddresses(hostname);
// now print them
string addressFamily;
foreach (IPAddress ip in ips)
{
addressFamily = ip.AddressFamily.ToString();
if (addressFamily.Equals("InterNetwork"))
{
// This is IPv4
Console.Writeline("IP: {0}", ip);
}
}
}