Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Cách hiển thị địa chỉ IP của máy tính bằng C#?

Sử dụng thuộc tính IPHostEntry.AddressList để lấy địa chỉ IP:

IPHostEntry myIP = Dns.GetHostEntry(hostName); 
IPAddress[] address = myIP.AddressList;

Thử mã sau để hiển thị địa chỉ IP:

Ví dụ

using System; 
using System.Net; 
class Program { 
    static void Main() { 
        String hostName = string.Empty; 
        hostName = Dns.GetHostName(); 
        Console.WriteLine("Hostname: " + hostName); 
        IPHostEntry myIP = Dns.GetHostEntry(hostName); 
        IPAddress[] address = myIP.AddressList; 
        for (int i = 0; i < address.Length; i++) { 
            Console.WriteLine("IP Address {1}: ", address[i].ToString()); 
        } 
        Console.ReadLine(); 
    } 
}