代码之家  ›  专栏  ›  技术社区  ›  Erx_VB.NExT.Coder

如何获得路由器名称和IP显示在Windows网络选项卡?(代码中)

  •  1
  • Erx_VB.NExT.Coder  · 技术社区  · 14 年前

    基本上,如果你去启动并单击计算机,然后单击左侧的网络链接,你会注意到右侧有几个类别,其中一个标题是“网络基础结构”,在这个类别中,我的路由器列出了,在我的情况下,它是 "LINKSYS WAG160N Wireless-N ADSL2+ Gateway" 当您右键单击并选择属性时,它会列出基本信息,例如内部/网关IP地址,在我的上 "192.168.1.1"

    我想知道如何在代码中检索这些信息,最好是一个WindowsAPI,以便我可以调用它使用一个遗留的VB6应用程序。另外,即使你只知道一个.NET版本或一个Delphi版本,请列出来,以及我可以在这两个代码。不过,我最终要寻找的答案是一个通过VB6访问这个的方法,因此可能是一个WinAPI调用(将upvote&选择这个作为答案),但是,如果我找不到遗留方法,也欢迎使用其他方法(我将upvote这些方法)。

    5 回复  |  直到 14 年前
        1
  •  1
  •   Bob77    14 年前

    需要的代码比我想要的要多一些。如果有更紧凑的方法,我自己也会感兴趣。

    据我所知,Windows通过UPnP获取信息。UPnP是一种基于UDP的Web服务。它有一些奇怪之处,因为它使用UDP多播,所以很难显式地编写代码,但是Windows提供了一个助手库。这个库并不适合VB6程序使用,但是通过一些技巧,您可以访问它的大部分功能。

    下面的代码是从我在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
    

    表1.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设备提供连接,您可能需要对此进行一些调整。

        2
  •  1
  •   dbasnett    14 年前

    您可以尝试捕获“routeprint-4”命令的输出并将其解析为默认路由。如果您使用的是IPv6,则将-4更改为-6。

        3
  •  1
  •   Chris Moschini    6 年前
    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();
    
        4
  •  0
  •   Denis Palnitsky    14 年前
        5
  •  0
  •   Eng. M.Hamdy    7 年前

    连接到网页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 "";
        }