说明:
(1) http://www.3322.org/dyndns/getip 这个网址可以获取本机IP,读取的内容就是本机IP
(2)方法经测试,可以实现。
(3)参考:http://www.cnblogs.com/ceachy/articles/CSharp_Retrive_Page_Document.html
两种方法:
(1)使用WebClient
private static string GetIP(String url) {
WebClient MyWebClient = new WebClient();
//获取或设置用于对向Internet资源的请求进行身份验证的网络凭据。
MyWebClient.Credentials = CredentialCache.DefaultCredentials;
//从指定网站下载数据
Byte[] pageData = MyWebClient.DownloadData(url);
//网站页面采用的是GB2312
string pageHtml = Encoding.Default.GetString(pageData);
//网站页面采用的是UTF-8
//string pageHtml = Encoding.UTF8.GetString(pageData);
return pageHtml;
}
(2)使用WebBrowser
WebBrowser web = new WebBrowser();
web.Navigate("http://www.3322.org/dyndns/getip");
web.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(web_DocumentCompleted);
//获取网页上的内容
void web_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {
WebBrowser web = (WebBrowser)sender;
HtmlElementCollection ElementCollection = web.Document.GetElementsByTagName("Body");
foreach (HtmlElement item in ElementCollection) {
ipstr += item.InnerText;
}
}
备注:
win7获取内网IP:
IPHostEntry ipe = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipa = ipe.AddressList[2];
string myIp = Convert.ToString(ipa);
原文地址:http://blog.csdn.net/u013816709/article/details/41960261