C#获取本机公网IP

时间:2022-10-04 16:06:38
 /// <summary>
/// 获取本机公网IP
/// </summary>
/// <returns></returns>
public static string GetIP_Lan()
{
string tempip = "127.0.0.1";
try
{
WebRequest wr = WebRequest.Create("http://www.ip138.com/ip2city.asp");
Stream s = wr.GetResponse().GetResponseStream();
StreamReader sr = new StreamReader(s, Encoding.Default);
string all = sr.ReadToEnd();
int start = all.IndexOf("[") + ;
int end = all.IndexOf("]", start);
tempip = all.Substring(start, end - start);
sr.Close();
s.Close();
}
catch
{
}
return tempip;
}