martes, 21 de febrero de 2017

Clase Visual Basic .NET con función para obtener datos GeoIP (Ip pública y localización) y función para obtener el nombre del host a partir de una IP

Imports System.Net

'http://www.vbforums.com/showthread.php?637319-VB-Net-Simple-function-to-get-external-IP-adress

Public Class clsExternalIPAddress
    Public Structure ExternalIPData
        Dim IP As String
        Dim CountryCode As String
        Dim CountryName As String
        Dim RegionCode As String
        Dim RegionName As String
        Dim City As String
        Dim TimeZone As String
        Dim Latitude As Double
        Dim Longitude As Double
    End Structure

    Public Function GeoIP(Optional IP As String = Nothing) As ExternalIPData
        Dim IPData As New ExternalIPData

        Using client = New WebClient()
            Try
                Dim strFile As String
                If IsNothing(IP) Then
                    strFile = client.DownloadString("http://freegeoip.net/xml")
                Else
                    strFile = client.DownloadString(String.Format("http://freegeoip.net/xml/{0}", IP))
                End If

                Dim response As XElement = XElement.Parse(strFile)

                With IPData
                    .IP = response.Element("IP").Value
                    .CountryCode = response.Element("CountryCode").Value
                    .CountryName = response.Element("CountryName").Value
                    .RegionCode = response.Element("RegionCode").Value
                    .RegionName = response.Element("RegionName").Value
                    .City = response.Element("City").Value
                    .TimeZone = response.Element("TimeZone").Value
                    .Latitude = CType(response.Element("Latitude").Value, Long)
                    .Longitude = CType(response.Element("Longitude").Value, Long)
                End With

            Catch ex As Exception
                Return Nothing
            End Try
        End Using

        Return IPData

    End Function

    Public Function GetExternalIP() As String
        Try
            Return GeoIP.IP
        Catch ex As Exception
            Console.WriteLine(ex.Message)
            Return ""
        End Try

    End Function

    Public Function GetHostNameFromIP() As String
        Try
            Dim host As System.Net.IPHostEntry
            host = System.Net.Dns.GetHostEntry(GeoIP.IP)
            Return host.HostName
        Catch ex As Exception
            Return ""
        End Try

    End Function

End Class

No hay comentarios:

Publicar un comentario

VBA Access. Redondeo de números decimales con el método medio redondeo. Alternativa a la función Round (bankers round)

 Private Function Redondeo(ByVal Numero As Variant, ByVal Decimales As Integer) As Double     'Aplica método medio redondeo (half round ...