通過外部網站返回得到內網外部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], 0, 0);
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 Nothing) Then
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