65.9K
CodeProject is changing. Read more.
Home

Getting the External IP Address

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.77/5 (11 votes)

Sep 3, 2012

CPOL
viewsIcon

84409

A very simple and short way to get the external IP address

Introduction

We connect to servers that give us our external IP address and try to parse the IP from returning HTML pages. But when servers make small changes on these pages or remove them, these methods stop working properly.

Here is a method that takes the external IP address using a server which has been alive for years and returns a simple response rapidly...

C#

private string getExternalIp()
{
    try
    {
        string externalIP;
        externalIP = (new WebClient()).DownloadString("http://checkip.dyndns.org/");
        externalIP = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))
                     .Matches(externalIP)[0].ToString();
        return externalIP;
    }
    catch { return null; }
}

VB.NET

Private Function GetExternalIp() As String
    Try
        Dim ExternalIP As String
        ExternalIP = (New WebClient()).DownloadString("http://checkip.dyndns.org/")
        ExternalIP = (New Regex("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")) _
                     .Matches(ExternalIP)(0).ToString()
        Return ExternalIP
    Catch
        Return Nothing
    End Try
End Function