获取本机外网ip和内网ip

时间:2023-03-09 07:52:53
获取本机外网ip和内网ip

  获取本机外网ip

   //获取本机的公网IP
public static string GetIP()
{
string tempip = "";
try
{
WebRequest request = WebRequest.Create("http://ip.qq.com/");
request.Timeout = ;
WebResponse response = request.GetResponse();
Stream resStream = response.GetResponseStream();
StreamReader sr = new StreamReader(resStream, System.Text.Encoding.Default);
string htmlinfo = sr.ReadToEnd();
//匹配IP的正则表达式
Regex r = new Regex("((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)\\.){3}(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|[1-9])", RegexOptions.None);
Match mc = r.Match(htmlinfo);
//获取匹配到的IP
tempip = mc.Groups[].Value; resStream.Close();
sr.Close();
}
catch (Exception err)
{
tempip = err.Message;
}
return tempip;
}

获取本机内网ip

 //获取内网IP
private string GetInternalIP()
{
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;
}