C#(局域网)获取外网IP

From: CikerBlog

Form图:


完成图:



只贴获取IP部分的代码:

private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = Dns.Resolve(Dns.GetHostName()).AddressList.GetValue(0).ToString(); //内网IP
textBox2.Text = GetIP(); //外网IP
}

static string GetIP()
{
Uri uri = new Uri("http://www.ciker.net/ip/index.asp");
System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = 0;
req.CookieContainer = new System.Net.CookieContainer();
req.GetRequestStream().Write(new byte[0], 0, 0);
System.Net.HttpWebResponse res = (System.Net.HttpWebResponse)(req.GetResponse());
StreamReader rs = new StreamReader(res.GetResponseStream(), System.Text.Encoding.GetEncoding("GB2312"));
string s = rs.ReadToEnd();
rs.Close();
req.Abort();
res.Close();
System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(s, @"您的IP:(?<IP>[0-9\.]*)");
if (m.Success)
{
return m.Groups["IP"].Value;
}
else
{
return "Failed..";
}
}

posted on 2008-04-08 19:02  live-evil  阅读(6221)  评论(3编辑  收藏  举报

导航