[C#] 網路基本應用

  • 4172
  • 0

摘要:[C#] 網路基本應用

一、取得 Local 主機的識別名稱

using System.Net;

namespace TestGetHostName {
    class Program {
        static void Main(string[] args) {
            try {
                // 取得Local主機的識別名稱
                string localHostName = Dns.GetHostName();
                Console.WriteLine(localHostName);                
            }
            catch (Exception ex) {
                Console.WriteLine(ex.Message);
            }

            Console.ReadLine();
        }
    }
}

二、取得 Local 主機的 IP Address

using System.Net;

namespace TestGetLocalIPAddress {
    class Program {        
        static void Main(string[] args) {
            string sHostName = string.Empty;
            IPHostEntry oIPHostEntry = null;

            // 取得本機名稱
            sHostName = Dns.GetHostName();
            
            // 取得本機的 IpHostEntry 物件[註1]
            oIPHostEntry = Dns.GetHostByName(sHostName);

            if (oIPHostEntry != null && oIPHostEntry.AddressList.Length > 0) {
                foreach (IPAddress ipAddress in oIPHostEntry.AddressList) {
                    Console.WriteLine(ipAddress.ToString());
                }
                Console.Read();
            }
           
        }
    }
}

不過這邊我發現,在編譯的時候會出現一個警告(如下圖),不過還是可以正確的執行。

Dns.GetHostByName 方法已經過時,建議使用 Dns.GetHostEntry ,不過,這個方法我有試用,感覺沒這麼直覺。

三小俠  小弟獻醜,歡迎指教