Используя NetworkInterface получить текущее имя соединения и IP-адрес для VPN - PullRequest
0 голосов
/ 28 февраля 2019

Я адаптирую приложение vpn vb6 для vb.net.Как получить с помощью NetworkInterface текущее имя и IP-адрес активного соединения?Я знаю, что если vpn активен, соединение Ethernet или wifi не должно быть активным, верно?Мое приложение должно перечислять текущее активное имя соединения и IP-адрес, независимо от того, используется ли соединение Windows vpn (должно отображаться имя vpn и ip), или OpenVPN (должно отображаться, скорее всего, имя как Ethernet 2), или приложение vpn (наиболее вероятное имякак Ethernet 2).

Ответы [ 2 ]

0 голосов
/ 01 марта 2019

Вот рабочий код, который у меня есть:

 Public Function GetConnectionList() As List(Of String())
        Dim conList As New List(Of String())
        Dim conName As String = "dummy"
        Dim last_conName As String = "dummy"
        Dim conIPstr As String = "dummy"
        Dim str As String

        conList.Clear()
        Dim nic As NetworkInterface() = NetworkInterface.GetAllNetworkInterfaces()

        If nic.GetLongLength(0) > 0 Then

            For Each netadapter As NetworkInterface In nic

                conName = netadapter.Name
                Dim strArr As String() = New String(2) {"dummy", "dummy", "dummy"}

                If Not conName.Contains("VirtualBox") _
                    And Not conName.Contains("Loopback") _
                    And conName <> "Ethernet" _
                    And conName <> "Wi-Fi" Then

                    strArr(0) = conName
                    If netadapter.OperationalStatus = OperationalStatus.Up Then
                        strArr(1) = "Current Sataus: Active"
                        Try
                            conIPstr = GetMyIPstr()
                        Catch e As Exception
                            MessageBox.Show("Error: Function GetConnectionList: Error returning IP Address" & vbCrLf & vbCrLf & e.Message)
                        End Try
                        strArr(2) = conIPstr
                    Else
                        strArr(1) = "Current Sataus: Not Active"
                        strArr(2) = "No IP Address"
                    End If

                    conList.Add(strArr)

                End If
            Next
        Else
            MessageBox.Show("Error: Function GetConnectionList: No Net Adapter List")
        End If

        Return conList

    End Function

     Private Function GetMyIPstr() As String
        Dim client As New WebClient
        Dim s As String = "No IP Address"
        '// Add a user agent header in case the requested URI contains a query.
        client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR1.0.3705;)")
        Dim baseurl As String = "http://checkip.dyndns.org/"
        ' with proxy server only:
        Dim proxy As IWebProxy = WebRequest.GetSystemWebProxy()
        proxy.Credentials = CredentialCache.DefaultNetworkCredentials
        client.Proxy = proxy
        Dim data As Stream
        Try
            data = client.OpenRead(baseurl)
        Catch ex As Exception
            MsgBox("open url " & ex.Message)
            Exit Function
        End Try
        Dim reader As StreamReader = New StreamReader(data)
        s = reader.ReadToEnd()
        data.Close()
        reader.Close()
        s = s.Replace("<html><head><title>Current IP Check</title></head><body>", "").Replace("</body></html>", "").ToString()
        'MessageBox.Show(s)
        'Me.Text = s
        Return s
    End Function
0 голосов
/ 28 февраля 2019

Нет, Windows показывает все интерфейсы, и активный должен быть хотя бы один из них добавляющим в vpn.Вызываете туннелирование vpn (частной сети virtuell) через ваше сетевое соединение.

   Dim interfaces As NetworkInformation.NetworkInterface() = NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()
  If interfaces.GetLongLength(0) > 0 Then
    For Each Interface As NetworkInformation.NetworkInterface In interfaces
      If String.Compare(Interface.Description, "Tap") > 0 And String.Compare(Interface.Description, "Teredo") < 0 Then
      End if
    Next
  End if

это несколько ссылок для активного соединения openvpn.Вы можете отладить его и посмотреть, если другие методы интерфейса лучше подходят для идентификации вашего vpn-соединения

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...