在同一网络vb.net中确定全局IP,C#

时间:2017-01-13 00:34:49

标签: c# vb.net networking

我的软件以三种不同的方式保存信息,具体取决于数据库连接的类型(1-Local / 2-Network / 3-Internet)。

我可以根据连接字符串中的服务器名称识别数据库连接的类型。

首先解决的问题是当客户键入全局地址而不是在服务器计算机上键入Localhost时。

我使用此功能检查地址是否属于同一台机器:

Public Function IsLocalIpAddress(host As String) As Boolean
    Try
        ' get host IP addresses
        Dim hostIPs As Net.IPAddress() = Net.Dns.GetHostAddresses(host)
        ' get local IP addresses
        Dim localIPs As Net.IPAddress() = Net.Dns.GetHostAddresses(Net.Dns.GetHostName())
        ' test if any host IP equals to any local IP or to localhost
        For Each hostIP As Net.IPAddress In hostIPs
            ' is localhost
            If Net.IPAddress.IsLoopback(hostIP) Then
                Return True
            End If
            ' is local address
            For Each localIP As Net.IPAddress In localIPs
                If hostIP.Equals(localIP) Then
                    Return True
                End If
            Next
        Next
    Catch
    End Try
    Return False
End Function

但是,当他从同一网络中的另一台计算机键入全局IP时,软件将连接识别为(Internet),而不是(网络)

所以我需要告诉我这个全局IP在同一个网络中,以使我的软件正确处理此连接。

1 个答案:

答案 0 :(得分:0)

我做了一些技巧,也许它暂时解决了我的问题

1- First Trick

Ping全局IP地址,如果RoundtripTime应该在同一网络中小于2毫秒(我在我的数据线上测试了大多数着名的网站,它们都在20以上)

Dim ping1 As New System.Net.NetworkInformation.Ping()
            Try
                Dim PingReply1 As System.Net.NetworkInformation.PingReply = ping1.Send(GetFormCs(SrcMCS, CsDataEnum.Server))
                If PingReply1.Status = Net.NetworkInformation.IPStatus.Success Then
                    If PingReply1.RoundtripTime() <= 2 Then
                        dbHost = Hst.Network
                        ForcedToNetwork = True
                    End If
                End If
                PingReply1 = Nothing
            Catch ex As Exception
            End Try
            ping1 = Nothing

2- Second Trick

I检查连接的DSN IP ...如果它等于服务器全局IP,则表示连接在同一网络中

Dim webCL As New System.Net.WebClient
    Dim PublicIP As String = ""
    Try
        Dim foo As New Xml.XmlDocument
        foo.LoadXml(System.Text.Encoding.ASCII.GetString((webCL.DownloadData("http://checkip.dyndns.org/"))))
        Dim curNode As Xml.XmlNode = foo.DocumentElement.FirstChild
        curNode = curNode.NextSibling
        response = curNode.InnerText.Remove(0, curNode.InnerText.IndexOf(":") + 1)
    Catch ex As Exception
        PublicIP = "ERROR"
    End Try
      If PublicIP = Database_Sever_IP Then
          If dbHost = Hst.Internet Then
              dbHost = Hst.Network
              ForcedToNetwork = True
          End If
      End If