Check Local IP Address [C#]
This example shows how to detect whether a host name or IP address belongs to local computer.
Get local computer name
Get local computer host name using static method Dns.GetHostName.
[C#]
string localComputerName = Dns.GetHostName();
Get local IP address list
Get list of computer IP addresses using static method Dns.GetHostAd¬dresses. To get list of local IP addresses pass local computer name as a parameter to the method.
[C#]
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
Check whether an IP address is local
The following method checks if a given host name or IP address is local. First, it gets all IP addresses of the given host, then it gets all IP addresses of the local computer and finally it compares both lists. If any host IP equals to any of local IPs, the host is a local IP. It also checks whether the host is a loopback address (localhost / 127.0.0.1).
[C#]
public static bool IsLocalIpAddress(string host)
{
try
{
IPAddress[] hostIPs = Dns.GetHostAddresses(host);
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress hostIP in hostIPs)
{
if (IPAddress.IsLoopback(hostIP)) return true;
foreach (IPAddress localIP in localIPs)
{
if (hostIP.Equals(localIP)) return true;
}
}
}
catch { }
return false;
}
You can test the method for example like this:
[C#]
IsLocalIpAddress("localhost");
IsLocalIpAddress("127.0.0.1");
IsLocalIpAddress("MyNotebook");
IsLocalIpAddress("192.168.0.1");
IsLocalIpAddress("NonExistingName");
IsLocalIpAddress("99.0.0.1");
private string ReturnIPAddress()
{
IPHostEntry host;
string localIP = "?";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
localIP = ip.ToString();
}
}
return localIP;
}