Alex Rivera | Logout

How to get the IP address of the server on which my C# application is running on?

Asked 2009-07-01T13:20:23.433
374

I am running a server, and I want to display my own IP address.

What is the syntax for getting the computer's own (if possible, external) IP address?

Someone wrote the following code.

IPHostEntry host;
string localIP = "?";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
    if (ip.AddressFamily.ToString() == "InterNetwork")
    {
        localIP = ip.ToString();
    }
}
return localIP;

However, I generally distrust the author, and I don't understand this code. Is there a better way to do so?

Edit
Report

2 Answers

8

I just thought that I would add my own, one-liner (even though there are many other useful answers already).


string ipAddress = new WebClient().DownloadString("http://icanhazip.com");

answered 2013-06-27T16:05:51.100
0

And this is to get all local IPs in csv format in VB.NET

Imports System.Net
Imports System.Net.Sockets

Function GetIPAddress() As String
    Dim ipList As List(Of String) = New List(Of String)
    Dim host As IPHostEntry
    Dim localIP As String = "?"
    host = Dns.GetHostEntry(Dns.GetHostName())
    For Each ip As IPAddress In host.AddressList
        If ip.AddressFamily = AddressFamily.InterNetwork Then
            localIP = ip.ToString()
            ipList.Add(localIP)
        End If
    Next
    Dim ret As String = String.Join(",", ipList.ToArray)
    Return ret
End Function
answered 2012-04-26T01:13:40.890

Your Answer