获取内网、通过外部网站返回得到内网外部IP (C#/VB.NET)

获取内网IP

 代码

通过外部网站返回得到内网外部IP 


C#版

static string GetIP()
{
    Uri             uri = new Uri("http://www.ikaka.com/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], 00);
    System.Net.HttpWebResponse res = (System.Net.HttpWebResponse)(req.GetResponse());
    StreamReader    rs  = new StreamReader(res.GetResponseStream(), System.Text.Encoding.GetEncoding("GB18030"));
    
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;
    
return string.Empty;
}



VB.NET 版

Function GetIP() As String 
        
Dim Cookies As Net.CookieContainer = Nothing 
        
Dim httpurl As String = "http://www.ikaka.com/ip/index.asp" 
        Dim code As String = "GB2312" 
        Dim Url As New System.Uri(httpurl) 
        
Dim SomeByte() As Byte = System.Text.Encoding.ASCII.GetBytes(""
        
Dim req As Net.HttpWebRequest = CType(Net.WebRequest.Create(Url), Net.HttpWebRequest) 
        req.Method = "POST" 
        req.ContentType = "application/x-www-form-urlencoded" 
        req.ContentLength = 0 
 
        
If Not (Cookies Is NothingThen 
            req.CookieContainer = Cookies 
        
Else 
            req.CookieContainer = New Net.CookieContainer 
            Cookies = req.CookieContainer 
        
End If 
        req.GetRequestStream.Write(SomeByte, 0, SomeByte.Length) 
        
Dim res As Net.HttpWebResponse = CType(req.GetResponse, Net.HttpWebResponse) 
        
Dim ReadStream As IO.StreamReader = New IO.StreamReader(res.GetResponseStream, System.Text.Encoding.GetEncoding(code)) 
        
Dim strLine As String 
        
Dim getstr As String 
        
Do 
            strLine = ReadStream.ReadLine 
            getstr &= strLine & vbCrLf 
        
Loop Until strLine Is Nothing 
        ReadStream.Close() 
        req.Abort() 
        res.Close() 
        
Dim reg As New System.Text.RegularExpressions.Regex("<span class=""en"">IP:\[(?<ipstr>.*)?\]\s*</span>", System.Text.RegularExpressions.RegexOptions.IgnoreCase) 
        
Dim m As System.Text.RegularExpressions.Match 
        m = reg.Match(getstr) 
        
If m.Success Then Return m.Groups("ipstr").Value.ToString 
    
End Function
原文地址:https://www.cnblogs.com/sofire/p/1760908.html