开发者

How to get the IP address of a machine in C#

How do I get 开发者_Python百科the IP address of a machine in C#?


IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());

Your machine doesn't have a single IP address, and some of the returned addresses can be IPv6.

MSDN links:

  • Dns.GetHostAddresses
  • IPAddress

Alternatively, as MSalters mentioned, 127.0.0.1 / ::1 is the loopback address and will always refer to the local machine. For obvious reasons, however, it cannot be used to connect to the local machine from a remote machine.


My desired answer was

string ipAddress = "";
if (Dns.GetHostAddresses(Dns.GetHostName()).Length > 0)
{
     ipAddress = Dns.GetHostAddresses(Dns.GetHostName())[0].ToString();
}


 IPHostEntry ip = DNS.GetHostByName (strHostName);
 IPAddress [] IPaddr = ip.AddressList;

 for (int i = 0; i < IPaddr.Length; i++)
 {
  Console.WriteLine ("IP Address {0}: {1} ", i, IPaddr[i].ToString ());
 }


 string hostName = Dns.GetHostName(); // Retrive the Name of HOST

           // Get the IP
            string myIP = Dns.GetHostByName(hostName).AddressList[0].ToString();

//use Following Namespace- using System.Net;


NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces(); //get all network interfaces
IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName()); // get all IP addresses based on the local host name

foreach (NetworkInterface adapter in adapters) //for each Network interface in addapters
{
    IPInterfaceProperties properties = adapter.GetIPProperties(); // get the ip properties from the adapter and store them into properties
    foreach (UnicastIPAddressInformation ip in properties.UnicastAddresses) // for each UnicastIPAddressInformation in the IPInterfaceProperties Unicast address( this assocaites the IP address with the correct adapter)
    {
        //if the operationalStatus of the adapter is up and the ip Address family is in the Internwork
        if ((adapter.Name == "Ethernet" || adapter.Name == "Ethernet 2") && (ip.Address.AddressFamily == AddressFamily.InterNetwork)) //test against the name of the adapter you want to get
        {
            ipAddress = ip.Address.ToString();
                        
        }//end if
    }//end inner for, the UnicastIPAddressInformation for
}


this worked in my case, anyone looking for a simple way, must try this syntax. Thanks

string hostName = Dns.GetHostName(); // Retrive the Name of HOST
Console.WriteLine(hostName);
// Get the IP
string myIP = Dns.GetHostByName(hostName).AddressList[0].ToString();
Console.WriteLine("My IP Address is :"+myIP);
Console.ReadKey();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜