说明:
(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);
根据IP获取所在地:
WebBrowser web = new WebBrowser();
web.Navigate("http://www.cz88.net/ip/index.aspx?ip="+myIP);
web.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(web_DocumentCompleted);
/// <summary>
/// 获取用户所在地 方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void web_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {
WebBrowser web = (WebBrowser)sender;
//获取所在地
HtmlElement heAddress = web.Document.GetElementById("cz_addr");
//获取操作系统
//HtmlElement heSystem = web.Document.GetElementById("cz_opt");
string[] abc = heAddress.InnerText.Split(' ');
lblAddress.Text = abc[0];
}
版权声明:本文为博主原创文章,未经博主允许不得转载。