標籤:
前言
在 Windows Form Application 裡對於取得 IP Address 有內網、外網兩種 IP Address ,如果只需要取得內網 IP Address ,可以透過使用 IPHostEntry 類別取得,而外網的話就必須要發送一個 Request 到一個可以取得 IP Address 的網站後再分析 Response 的內容,這個網站可以自己做或者使用現成的,如 http://www.whatismyip.com.tw/ 。
另外,在使用 Socket 通訊的情況下,也有可能有需要知道前來連結的用戶端的 IP Address 是什麼,這時就可以使用 Socket.RemoteEndPoint 屬性來取得遠程 IP 位址和通訊連接埠編號,以下就列出範例代碼看看該如何使用。
範常式序代碼
/// <summary> /// 取得外網 IP Address /// </summary> /// <returns></returns> private string GetExtranetIPAddress() { HttpWebRequest request = HttpWebRequest.Create("http://www.whatismyip.com.tw") as HttpWebRequest; request.Method = "GET"; request.ContentType = "application/x-www-form-urlencoded"; request.UserAgent = "Mozilla/5.0"; string ip = string.Empty; WebResponse response = request.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream())) { string result = reader.ReadToEnd(); string pattern = @"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"; ip = Regex.Match(result, pattern).ToString(); } return ip; // result: 210.125.21.xxx }
取得外網 IP Address
/// <summary> /// 取得本機 IP Address /// </summary> /// <returns></returns> private List<string> GetHostIPAddress() { List<string> lstIPAddress = new List<string>(); IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName()); foreach (IPAddress ipa in IpEntry.AddressList) { if (ipa.AddressFamily == AddressFamily.InterNetwork) lstIPAddress.Add(ipa.ToString()); } return lstIPAddress; // result: 192.168.1.17 ...... }
取得本機 IP Address
/// <summary>/// 執行伺服器監聽/// </summary>public static void RunServer() { // 建立X509憑證 ServerCertificate = new X509Certificate(Certificate, "ssl"); // 監聽任何IP Address來的訊息 listener = new TcpListener(System.Net.IPAddress.Any, 17170); // 開啟監聽 listener.Start(); while (IsRun) { TcpClient client = listener.AcceptTcpClient(); ProcessClient(client); }}/// <summary>/// 接收用戶端訊息處理並回複/// </summary>/// <param name="pClient"></param>private static void ProcessClient(TcpClient pClient){ SslStream sslStream = new SslStream(pClient.GetStream(), true); // 取得串連者 IP 與 Port IPEndPoint point = pClient.Client.RemoteEndPoint as IPEndPoint; string ip = point.Address.ToString(); // result: 127.0.0.1 string port = point.Port.ToString(); // result: 55236 // do something...}
Socket 取得遠程 IP Address 與 Port
string tempIP =string.Empty;if (System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList.Length >1) tempIP = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList[1].ToString();
如果是ADSL上網,擷取公網ip
C#取得內網IP、外網IP、用戶端IP方法