簡體   English   中英

如何獲得Windows網絡選項卡中顯示的路由器名稱和IP? (在代碼中)

[英]How to get Router Name & IP as shown in Windows Network Tab? (in Code)

基本上,如果轉到“開始”並單擊“計算機”,然后單擊左側的“網絡”鏈接,您會在右側看到幾個類別,其中一個類別為“網絡基礎結構”,在該類別中,列出了路由器,在我的情況下,它是"LINKSYS WAG160N Wireless-N ADSL2+ Gateway" ,右鍵單擊並選擇屬性時,它列出了諸如內部/網關IP地址之類的基本信息,而在我看來,它是"192.168.1.1"

我想知道如何在代碼中檢索此信息,最好是Windows API,以便我可以使用舊版VB6應用程序調用它。 另外,即使您只知道.NET版本或Delphi版本,也請列出並在其中進行編碼。 但是,我最終尋求的答案是通過VB6訪問此方法的方法,因此可能是WinAPI調用(將投票並選擇它作為答案),但是,如果我找不到舊版方法,也可以使用其他方法方法(我會投票贊成)。

多謝你們 :)

您可以嘗試捕獲“ route print -4”命令的輸出並將其解析為默認路由。 如果使用的是IPv6,則將-4更改為-6。

需要的代碼比我想要的多。 如果有更緊湊的方法,我會對自己感興趣。

據我了解,Windows通過UPnP獲取信息。 UPnP充當一種基於UDP的Web服務。 它具有怪癖,因為它使用UDP多播,因此很難進行顯式編碼,但是Windows提供了一個幫助程序庫。 這個庫不能很好地“包裝”成VB6程序,但是通過一些技巧,您可以訪問其大多數功能。

編寫以下示例,以便可以在Win XP以及更高版本的Windows上進行編譯。 庫的Win XP版本缺少關鍵的typelib信息,該信息阻止VB6使用其提供的所有功能。 在Vista中,此問題已得到糾正,但是對於此應用程序,我們不需要其提供的完整回調功能。 如果需要完全訪問權限,則可以使用外部typelib,或者可以在Vista或更高版本上進行編譯。 在Vista上編譯的程序可以在XP上正常工作。

下面的代碼是從VB6服務器中用於UPnP NAT端口映射的較大類中提取的。 該子集可能會滿足您的要求。

UPnPNAT.cls

Option Explicit
'Requires reference to:
'
'   UPnP 1.0 Type Library (Control Point)
'

Private Const CONN_SVCTYPEID_URI As String = "urn:schemas-upnp-org:service:WANIPConnection:1"
Private Const CONN_ID_URI As String = "urn:upnp-org:serviceId:WANIPConn1"

Private UDFinder As UPNPLib.UPnPDeviceFinder
Private WithEvents UNCBs As UPnPNATCBs
Private findData As Long
Private blnSuccess As Boolean

Public Event Result(ByVal Success As Boolean, ByVal FriendlyName As String, ByVal IP As String)

Public Sub Fetch()
    blnSuccess = False
    Set UDFinder = New UPNPLib.UPnPDeviceFinder
    Set UNCBs = New UPnPNATCBs
    findData = CallByName(UDFinder, "CreateAsyncFind", VbMethod, CONN_SVCTYPEID_URI, 0, UNCBs)
    UDFinder.StartAsyncFind findData
End Sub

Private Sub UNCBs_DeviceAdded(ByVal Device As UPNPLib.IUPnPDevice)
    Dim Services As UPNPLib.UPnPServices
    Dim Service As UPNPLib.UPnPService
    Dim varInActionArgs, varOutActionArgs
    Dim strFriendlyName As String
    Dim strIP As String

    strFriendlyName = Device.FriendlyName
    On Error Resume Next
    Set Services = Device.Services
    If Err.Number = 0 Then
        On Error GoTo 0
        With Services
            If .Count > 0 Then
                On Error Resume Next
                Set Service = .Item(CONN_ID_URI)
                If Err.Number = 0 Then
                    On Error GoTo 0
                    ReDim varInActionArgs(0 To 0)
                    ReDim varOutActionArgs(0 To 0)
                    Service.InvokeAction "GetExternalIPAddress", _
                                         varInActionArgs, _
                                         varOutActionArgs
                    strIP = varOutActionArgs(0)
                    blnSuccess = True
                Else
                    On Error GoTo 0
                End If
            End If
        End With
    Else
        On Error GoTo 0
    End If

    UDFinder.CancelAsyncFind findData
    RaiseEvent Result(blnSuccess, strFriendlyName, strIP)
    Set UDFinder = Nothing
    Set UNCBs = Nothing
End Sub

Private Sub UNCBs_SearchComplete()
    If Not blnSuccess Then
        RaiseEvent Result(False, "", "")
    End If
End Sub

UPnPNATCBs.cls

Option Explicit

Public Event DeviceAdded(ByVal Device As UPNPLib.IUPnPDevice)
Public Event DeviceRemoved(ByVal UDN As String)
Public Event SearchComplete()

Public Sub IDispatchCallback( _
    ByVal pDevice As Variant, _
    ByVal bstrUDN As Variant, _
    ByVal lType As Variant)
    'NOTE: Must be dispID = 0, i.e. the default method of the class.

    Select Case lType
        Case 0
            RaiseEvent DeviceAdded(pDevice)
        Case 1
            RaiseEvent DeviceRemoved(bstrUDN)
        Case 2
            RaiseEvent SearchComplete
    End Select
End Sub

Form1.frm

Option Explicit

Private WithEvents UN As UPnPNAT

Private Sub Form_Load()
    Set UN = New UPnPNAT
    lblStatus.Caption = "Searching..."
    UN.Fetch
End Sub

Private Sub UN_Result(ByVal Success As Boolean, ByVal FriendlyName As String, ByVal IP As String)
    If Success Then
        lblStatus.Caption = FriendlyName & " " & IP
    Else
        lblStatus.Caption = "Failed"
    End If
End Sub

如果您有多個在網絡中提供連接的UPnP設備,則可能需要對此進行一些調整。

if (!NetworkInterface.GetIsNetworkAvailable())
    return "Not connected.";

var networkDevices = NetworkInterface.GetAllNetworkInterfaces();
if (networkDevices.Length == 0)
    return "No network devices.";

networkDevices = networkDevices
    .Where(n => n.OperationalStatus == OperationalStatus.Up
        || n.OperationalStatus == OperationalStatus.Dormant)
    .ToArray();
if (networkDevices.Length == 0)
    return "Network not connected.";

networkDevices = networkDevices
    .Where(n => n.Supports(NetworkInterfaceComponent.IPv4))
    .ToArray();
if (networkDevices.Length == 0)
    return "No IPv4 network found.";

var router = networkDevices.First().GetIPProperties()
    .GatewayAddresses.First();

var routerIp = router.Address.ToString();

連接到網頁http:[ip]。 該網頁的標題作為設備名稱(設備型號)。 這適用於顯示登錄頁面的設備。 如果設備希望通過請求獲取用戶名和密碼,則會發生WebException,並且您可以讀取WebException.Response.Headers [“ WWW-Authenticate”],其中包含字符串:Basic realm =“ X”,其中X是描述設備的字符串。

        private string GetDeviceName(string ip)
    {
        WebClient myWebClient = new WebClient(1000);
        try
        {
            System.IO.Stream s = myWebClient.OpenRead("http://" + ip);
            var sr = new System.IO.StreamReader(s);
            while (!sr.EndOfStream)
            {
                var L = sr.ReadLine();
                var sb = new StringBuilder();
                var st = 0;
                var end = 0;
                if ((st = L.ToLower().IndexOf("<title>")) != -1)
                {
                    sb.Append(L);
                    while ((end = L.ToLower().IndexOf("</title>")) == -1)
                    {
                        L = sr.ReadLine();
                        sb.Append(L);
                    }
                    sr.Close();
                    s.Close();
                    myWebClient.Dispose();
                    var title = sb.ToString().Substring(st + 7, end - st - 7);
                    Regex r = new Regex("&#[^;]+;");
                    title = r.Replace(title, delegate (Match match)
                    {
                        string value = match.Value.ToString().Replace("&#", "").Replace(";", "");
                        int asciiCode;
                        if (int.TryParse(value, out asciiCode))
                            return Convert.ToChar(asciiCode).ToString();
                        else
                            return value;
                    });
                    return $"Router/AP ({title})";
                }
            }
            sr.Close();
            s.Close();
            myWebClient.Dispose();
        }
        catch (System.Net.WebException ex)
        {
            var response = ex.Response as HttpWebResponse;
            if (response == null)
                return "";

            var name = response.Headers?["WWW-Authenticate"]?.Substring(12).Trim('"');
            myWebClient.Dispose();
            return name;
        }
        return "";
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM