执行效果,“Go”获得外网IP,下边的textbox显示连接网站后返回的html代码!外网IP就是从中提取的。
主文件GetIP.cs
usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Management;
usingSystem.Windows.Forms;
usingSystem.Net;
usingSystem.IO;
namespaceIPGet
...{
publicpartialclassForm_IP:Form
...{
publicForm_IP()
...{
InitializeComponent();
ManagementClassmc=newManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollectionmoc=mc.GetInstances();
foreach(ManagementObjectmoinmoc)
...{
if(!(bool)mo["IPEnabled"])
continue;
this.textBoxMAC.Text ="---" mo["MACAddress"].ToString();
string[]addresses=(string[])mo["IPAddress"];
string[]subnets=(string[])mo["IPSubnet"];
//displayIPAddresses
foreach(stringsadinaddresses)
this.textBoxLocalIP.Text ="---" sad "";
//displaySubNetsmask
foreach(stringsubinsubnets)
this.textBoxSub.Text ="---" sub "";
}
}
privatestringGetIP()
...{
Uriuri=newUri("http://www.ciker.net/ip/index.asp");
HttpWebRequestreq=(HttpWebRequest)WebRequest.Create(uri);
req.Method="POST";
req.ContentType="application/x-www-form-urlencoded";
req.ContentLength=0;
req.CookieContainer=newSystem.Net.CookieContainer();
req.GetRequestStream().Write(newbyte[0],0,0);
HttpWebResponseres=(HttpWebResponse)(req.GetResponse());
StreamReaderrs=newStreamReader(res.GetResponseStream(),System.Text.Encoding.GetEncoding("GB2312"));
try
...{
strings=rs.ReadToEnd();
this.textBox.Text=s;
rs.Close();
req.Abort();
res.Close();
System.Text.RegularExpressions.Matchm=System.Text.RegularExpressions.Regex.Match(s,@"您的IP:(?<IP>[0-9.]*)");
if(m.Success)
...{
returnm.Groups["IP"].Value;
}
else
...{
return"没有连接上主机";
}
}