如何使用 C# 顯示機器的 IP 地址?


使用 IPHostEntry.AddressList 屬性獲取 IP 地址 −

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

嘗試以下程式碼以顯示 IP 地址 −

示例

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();
   }
}

更新於: 20-6 月-2020

622 次瀏覽

開啟您的 職業生涯

完成課程即可獲得認證

開始
廣告