Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get IPv4 and IPv6 address of local machine?

I am developing a windows application and I need to find the IPv4 and IPv6 address of local machine. OS can be XP or Windows 7.

I got a solution for getting MAC address like,

string GetMACAddress()
{
    var macAddr =
        (
            from nic in NetworkInterface.GetAllNetworkInterfaces()
            where nic.OperationalStatus == OperationalStatus.Up
            select nic.GetPhysicalAddress().ToString()
        ).FirstOrDefault();

    return macAddr.ToString();
}

This is working in all OS.

What is the correct way to get IPv4 and IPv6 address that work on XP and WINDOWS 7?

like image 952
Matt Avatar asked Jan 17 '23 03:01

Matt


1 Answers

string strHostName = System.Net.Dns.GetHostName();;
IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);
IPAddress[] addr = ipEntry.AddressList;
Console.WriteLine(addr[addr.Length-1].ToString());
if (addr[0].AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
            {
                Console.WriteLine(addr[0].ToString()); //ipv6
            }
like image 165
Habib Avatar answered Jan 22 '23 22:01

Habib