1、VB 中获取电脑外网 IP 的源代码大家知道每个能上网的电脑都拥有一个自己的 IP,如果你是位于局域网呢,那么你的ip 可能是 192.168.*.*或者 10.*.*.*之类的,这样的 IP 外网是无法访问的,只能在同一个网段之间互访。而这时在自己电脑的 CMD 上 ipconfig /all 看见自己的ip 就是内网 IP,而我们是以外网 IP 访问网络的,那么我们怎么获取外网 IP 呢?这需要我们访问一些专门的网站来获取。这里我收集了几个,拿来共享。http:/members.3322.org/dyndns/getiphttp:/ IP 正确,当一个不能反馈 IP 时就试着从另外一个网站
2、获取。给段代码供参考获取公网 IPPrivate Declare Function InternetOpen Lib “wininet.dll“ Alias “InternetOpenA“ ( _ByVal sAgent As String, ByVal lAccessType As Long, _ByVal sProxyName As String, ByVal sProxyBypass As String, _ByVal lFlags As Long) As LongPrivate Declare Function InternetOpenUrl Lib “wininet.dll“ Ali
3、as “InternetOpenUrlA“ ( _ByVal hInternetSession As Long, ByVal sUrl As String, _ByVal sHeaders As String, ByVal lHeadersLength As Long, _ByVal lFlags As Long, ByVal lContext As Long) As LongPrivate Declare Function InternetReadFile Lib “wininet.dll“ ( _ByVal hFile As Long, ByVal sBuffer As String, _
4、ByVal lNumBytesToRead As Long, _lNumberOfBytesRead As Long) As IntegerPrivate Declare Function InternetCloseHandle Lib “wininet.dll“ ( _ByVal hInet As Long) As IntegerPrivate Const INTERNET_FLAG_NO_CACHE_WRITE = &H4000000Private Declare Function URLDownloadToFile Lib “urlmon“ Alias “URLDownloadToFil
5、eA“ (ByVal pCaller As Long, ByVal szURL As String, ByVal szFileName As String, ByVal dwReserved As Long, ByVal lpfnCB As Long) As LongPublic Function GetSub() As StringDim wburl$, wburl2$, X1, X2, X3, X4On Error GoTo errwburl = “http:/ = GetUrlFile(wburl)If InStr(1, wburl, “无法找到该页“) = 0 ThenX1 = InS
6、tr(1, wburl, “)X2 = InStr(1, wburl, “)X1 = Mid(wburl, X1, X2 - X1)X1 = Replace(X1, “, “)X1 = Replace(X1, “ “, “)X1 = Replace(X1, vbCrLf, “)GetSub = X1Exit FunctionEnd Ifwburl2 = “http:/ = GetUrlFile(wburl2)If InStr(1, wburl2, “无法找到该页“) = 0 ThenX3 = InStr(1, wburl2, “)X4 = InStr(1, wburl2, “)X3 = Mid
7、(wburl2, X3, X4 - X3)X3 = Replace(X3, “, “)X3 = Replace(X3, “ “, “)X3 = Replace(X3, vbCrLf, “)GetSub = X3Exit FunctionElseGetSub = “127.0.0.1“End Iferr:GetSub = “127.0.0.1“End FunctionPrivate Function GetUrlFile(stUrl As String) As StringDim lgInternet As Long, lgSession As LongDim stBuf As String *
8、 1024Dim inRes As IntegerDim lgRet As LongDim stTotal As StringstTotal = vbNullStringlgSession = InternetOpen(“VBTagEdit“, 1, vbNullString, vbNullString, 0)If lgSession ThenlgInternet = InternetOpenUrl(lgSession, stUrl, vbNullString, _0, INTERNET_FLAG_NO_CACHE_WRITE, 0)If lgInternet ThenDoinRes = InternetReadFile(lgInternet, stBuf, 1024, lgRet)stTotal = stTotal & Mid$(stBuf, 1, lgRet)Loop While (lgRet 0)End IfinRes = InternetCloseHandle(lgInternet)End IfGetUrlFile = stTotalEnd Function使用方法:在 form 中调用 GetSub 就行了List1.AddItem (“公网 IP:“ & GetSub + “)