Obtener IP Publica en VB.NET y CSharp

New product

How to know the public IP written on vb.net and c #. Source code available.

Get Public IP in VB.NET and C #

Many times we see ourselves in the difficulty of knowing the public IP of the machine where we run our program or application. For these cases, the NET platform provides us with tools to work with the http protocol and with the same ability to read content from the WEB.

So in this article I put to work in making a class that allows me to know the IP of a machine where the function is executed. I show it below:

We created a function that reads WEB content and I call it AsyncDarContenidoHtmlWebsite.

In Visual Basic NET:

    Public Shared Async Function AsyncDarContenidoHtmlWebsite(ByVal mURL As String,
Optional TiempoEspera As Integer = 5000) As Task(Of String)
Dim PeticionWeb As System.Net.WebRequest
Dim RespuestaWeb As System.Net.HttpWebResponse
Dim datos As String = ""

'Ejecutando la tarea asincrona.
Await Task.Run(Sub()
Try
PeticionWeb = System.Net.WebRequest.Create(mURL)
PeticionWeb.Timeout = TiempoEspera
RespuestaWeb = PeticionWeb.GetResponse()
datos =
New System.IO.StreamReader(RespuestaWeb.GetResponseStream()).ReadToEnd()
Catch ex As System.Net.WebException
'ex.Status .
datos = "Error " & ex.Status.ToString
End Try
End Sub
)
If datos = "" Then
datos = "Error "
End If
Return
datos

End Function

In C#:

public static async Task<string> AsyncDarContenidoHtmlWebsite(string mURL, int TiempoEspera = 5000)
{
System.Net.
WebRequest PeticionWeb;
System.Net.
HttpWebResponse RespuestaWeb;
string datos = "";

// Ejecutando la tarea asincrona.
await Task.Run(() =>
{
try
{
PeticionWeb = System.Net.
WebRequest.Create(mURL);
PeticionWeb.Timeout = TiempoEspera;
RespuestaWeb = (
HttpWebResponse)PeticionWeb.GetResponse();
datos =
new System.IO.StreamReader(RespuestaWeb.GetResponseStream()).ReadToEnd();
}
catch (WebException ex)
{
datos =
"Error " + ex.Status.ToString();
}
});
if (datos == "") datos = "Error ";
return datos;
}

In general, a task of this kind takes time to run, so we must run them in the background so that, in the case of using graphical interface, it does not lock and allows the user to do other tasks while it is finished.

As mentioned above, the function is implemented asynchronously. Sure, but in the source file is the normal synchronous implementation so they can compare.

Another interesting feature that he created was to search for IP in a text. Which is:

   Public Shared Function BuscarIPenTexto(Texto As String) As String
'Texto = Texto.Replace(" ", "")
Texto &= " "
Dim ips As String = ""
Dim contPuntos As Integer
For Each
c As String In Texto
Select Case c
Case "0" To "9"
ips &= c
Case "."
contPuntos += 1
ips &= c
Case Else
If
contPuntos = 3 Then Return ips
ips =
""
contPuntos = 0
End Select
Next
Return
""
End Function

It is quite simple. What it does is search the text for numbers and points. If the sequence does not match IPv4 IP addresses, it jumps to the next. It will return the first valid match.

And finally the AsyncDarMiIPPublica master function that is responsible for delivering the public IP.

    Public Shared Async Function AsyncDarMiIPPublica() As Task(Of String)
'Proveedores de servicio
'
'Importante:
'Es conveniente de que si tienes una web propia, realices un
'pagina que de la ip y montarla en tu hosting. Para asi, evitar
'el uso de el ancho de banda del dueño del servicio.
'
'Los sitios mencionados a continuación ofrecen el servicio sin
'anuncios, por lo que no existe problemas por falta de monetización.
'URL-> http://checkip.dyndns.org
'URL-> http://ipinfo.info/html/geolocation_2.php
'URL-> http://ipinfo.info/google/

Dim listaProveedores As New List(Of String)
Dim MiIP As String = ""
Dim OcurrioError As Boolean
Dim
ContenidoWeb As String

'Se agregan las URL al listado de comprobación,
'Si falla una, se intenta con la otra.
listaProveedores.Add("http://checkip.dyndns.org")
listaProveedores.Add(
"http://ipinfo.info/google/")
listaProveedores.Add(
"http://ipinfo.info/html/geolocation_2.php")

For Each Proveedor As String In listaProveedores
OcurrioError =
False
ContenidoWeb = Await AsyncDarContenidoHtmlWebsite(Proveedor)
If ContenidoWeb.StartsWith("Error") Then
'Si ocurre el error se intenta con la
'siguiente URL de la lista
OcurrioError = True
Continue For
Else
MiIP = BuscarIPenTexto(ContenidoWeb)
OcurrioError =
False
Exit For
End If
Next
If
OcurrioError Then MiIP = "Error"
Return MiIP
End Function

Basically what I do is go through a list of IP service providers published on the internet, so they give me the IP address of the machine where I'm calling them from. But beware, I'm just listing those that do not have publicity, it's not ethical with the website's publisher, to use a service that depends on advertising.

So if one provider fails me, I jump to the next, so I will securely obtain my IP. And this function is also asynchronous, to avoid user interface blockages and to be able to track it, such as canceling the operation if it lasts too long, or if the user wants to cancel.

Implementation of the code

The implementation of this class is quite simple, in console mode we can do it this way:

Paste the code in the Main procedure.

        Dim tokenSourse As New Threading.CancellationTokenSource()
Dim t As Task
Dim MiIP As String = ""
Dim ib As Integer
Dim
b() As String = {"-", "", "|", "/"}
Dim tEspera As New Stopwatch

tEspera.Start()
'Sub-proceso secundario que realiza la tarea de buscar la Ip Pública
t = Task.Factory.StartNew(Sub()
MiIP =
WebHelper.AsyncDarMiIPPublica().Result
End Sub,
tokenSourse.Token)

'Proceso sincrono que espera a que se de el IP
'Como estamos en modo consola y no tenemos interfaz grafica
'simulamos una. jejejeje.
Do
Console.CursorLeft = 0
Console.CursorTop = 1
ib += 1
If ib > b.GetUpperBound(0) Then ib = 0
'Mensaje de barrita rotativa. ;)
EscribeLinea("Obteniendo informacion..." & b(ib))
Threading.
Thread.Sleep(100)
'Esperamos 10 segundos que se complete la tarea, sino
'mostramos el mensaje y la posibilidad de cancelar.
If tEspera.Elapsed.TotalSeconds > 10 Then
EscribeLinea(" ¡Vaya! se esta tardando mucho...presiona ""c"" si deseas cancelar.")
If Console.KeyAvailable AndAlso
Console.ReadKey(True).Key = ConsoleKey.C Then
MiIP = ""
'Se cancela el proceso en segundo plano y salimos de la interfaz grafica XD.
tokenSourse.Cancel()
Exit Do
End If
Else
'Se consume el buffer de teclas.
If Console.KeyAvailable Then Console.ReadKey(True)
End If
Loop Until
MiIP <> ""


'Se muestra la IP pública
Console.Clear()
Console.CursorLeft = 0
Console.CursorTop = 1
If MiIP = "" Then
EscribeLinea("Proceso cancelado")
Else
EscribeLinea("Mi ip " & MiIP)
End If
EscribeLinea("Presiona enter para continuar.")
LeeLinea()

And... It's all, I think with this code more than enough to create robust Apps that require this service. It is also implemented for C # and can be found in the downloadable file below.

Download zone:


download intarce hidraulica

Totally free of viruses and malicious software, so do not wait any longer to download it now.

Do not forget to give us an opinion on this program, to improve the content.

Written for

Elimar García

Eli Programa.

20/10/2018

Grade 
10/21/2018

Excelente

Gran post

    Write your review!

    Write a review

    Obtener IP Publica en VB.NET y CSharp

    Obtener IP Publica en VB.NET y CSharp

    How to know the public IP written on vb.net and c #. Source code available.

    Ask a question

    NO registration required!

    If the question you have has not yet been answered here, use the form below to ask something about this addon.

    (optional)
    *(Required to be notified when an answer is available)

    If the download link redirects to another product that is not described in the article or is broken, report it using our Reporting Form

    RelatedProducts