c#获得服务器的外网ip、内网ip
- 时间:2015年04月02日 15:27:12 来源:魔法猪系统重装大师官网 人气:10922
如下代码可以获得服务器所在内网的内网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;
如果要获得服务器的公网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("