Lấy thông tin IP của máy local

 

/// <summary>
/// Gets IP addresses of the local computer
/// </summary>
public string GetLocalIP()
{
    string _IP = null;

    // Resolves a host name or IP address to an IPHostEntry instance.
    // IPHostEntry - Provides a container class for Internet host address information. 
    System.Net.IPHostEntry _IPHostEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());

    // IPAddress class contains the address of a computer on an IP network. 
    foreach (System.Net.IPAddress _IPAddress in _IPHostEntry.AddressList)
    {
        // InterNetwork indicates that an IP version 4 address is expected 
        // when a Socket connects to an endpoint
        if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
        {
            _IP = _IPAddress.ToString();
        }
    }
    return _IP;
}

 

Ví dụ sử dụng:

 

Console.WriteLine("Local computer IP address : " + GetLocalIP());

Đoạn code này sử dụng để lấy ip của máy có nhiều địa chỉ ip

/// <summary>
/// Gets IP addresses object list from the local computer
/// </summary>
public System.Net.IPAddress[] GetLocalIPList()
{
    // Resolves a host name or IP address to an IPHostEntry instance.
    // IPHostEntry - Provides a container class for Internet host address information. 
    System.Net.IPHostEntry _IPHostEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());

    return _IPHostEntry.AddressList;
}

Ví dụ sử dụng:

// display all IP addresses of local machine
foreach (System.Net.IPAddress _IPAddress in GetLocalIPList())
    Console.WriteLine(_IPAddress.ToString());


// display all IP addresses of local machine with addressing scheme
foreach (System.Net.IPAddress _IPAddress in GetLocalIPList())
    Console.WriteLine(_IPAddress.AddressFamily.ToString() + " = " +  _IPAddress.ToString());