要獲得路由器的外網(或公網)IP地址,一般的做法是先訪問外網的一個網站(如,由這個網站記錄下該路由器的外網IP地址,然後再返回結果。其實對於某些型號的路由器,我們完全可以直接讀取它的外網IP,比如TP-LINK,下面是VB.NET實現代碼,另附串連和斷線兩段代碼:
''' <summary> ''' 串連外網 ''' </summary> Public Sub Connect(ByVal UserName As String, ByVal Password As String) Dim xHttp As Object = CreateObject("MSXML2.XMLHTTP") xHttp.open("GET", "http://192.168.2.2/userRpm/StatusRpm.htm?Connect=連 接&wan=1", False, UserName, Password) xHttp.send() System.Runtime.InteropServices.Marshal.ReleaseComObject(xHttp) xHttp = Nothing End Sub ''' <summary> ''' 斷開外網串連 ''' </summary> Public Sub Disconnect(ByVal UserName As String, ByVal Password As String) Dim xHttp As Object = CreateObject("MSXML2.XMLHTTP") xHttp.open("GET", "http://192.168.2.2/userRpm/StatusRpm.htm?Disconnect=斷 線&wan=1", False, UserName, Password) xHttp.send() System.Runtime.InteropServices.Marshal.ReleaseComObject(xHttp) xHttp = Nothing End Sub ''' <summary> ''' 獲得外網IP ''' </summary> Public Function GetWanIp(ByVal UserName As String, ByVal Password As String) As String Dim strIP As String = "0.0.0.0" Dim xHttp As Object = CreateObject("MSXML2.XMLHTTP") xHttp.open("GET", "http://192.168.2.2/userRpm/StatusRpm.htm?Connect=連 接&wan=1", False, UserName, Password) xHttp.send() If xHttp.readyState = 4 AndAlso xHttp.Status = 200 Then Dim strHTML As String = Text.Encoding.Default.GetString(xHttp.responseBody) strHTML = strHTML.Substring(strHTML.IndexOf("var wanPara")) strHTML = strHTML.Substring(0, strHTML.IndexOf(";")) strIP = strHTML.Split(",")(2).Replace("""", "").Trim() End If System.Runtime.InteropServices.Marshal.ReleaseComObject(xHttp) xHttp = Nothing Return strIP End Function
另,對於串連外網和斷開外網串連操作,可能有的朋友已在某些部落格中見到過,而我還在這兒標識為“原創”,原因是當初我未找到類似代碼,通過攔截和分析HTTP資料包,才寫了出來,後來發現網上有類似的,大概算是”英雄所見略同“吧。