如下代碼可以獲得服務(wù)器所在內(nèi)網(wǎng)的內(nèi)網(wǎng)ip
IPHostEntry host; string localIP = "?"; host = Dns.GetHostEntry(Dns.GetHostName()); foreach (IPAddress ip in host.AddressList) { if (ip.AddressFamily.ToString() == "InterNetwork") { localIP = ip.ToString(); break; } } return localIP;
如果要獲得服務(wù)器的公網(wǎng)ip,可以使用下面代碼:
public string GetPublicIP() { String direction = ""; WebRequest request = WebRequest.Create("http://checkip.dyndns.org/"); using (WebResponse response = request.GetResponse()) using (StreamReader stream = new StreamReader(response.GetResponseStream())) { direction = stream.ReadToEnd(); } //Search for the ip in the html int first = direction.IndexOf("Address: ") + 9; int last = direction.LastIndexOf("</body>"); direction = direction.Substring(first, last - first); return direction; }