In the internet there are several places that show you how to get an IP address. And a lot of them look like this example:
String strHostName = string.Empty;
There is already many of answer, but I m still contributing mine one:
public static IPAddress LocalIpAddress() {
Func<IPAddress, bool> localIpPredicate = ip =>
ip.AddressFamily == AddressFamily.InterNetwork &&
ip.ToString().StartsWith("192.168"); //check only for 16-bit block
return Dns.GetHostEntry(Dns.GetHostName()).AddressList.LastOrDefault(localIpPredicate);
}
One liner:
public static IPAddress LocalIpAddress() => Dns.GetHostEntry(Dns.GetHostName()).AddressList.LastOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork && ip.ToString().StartsWith("192.168"));
note: Search from last because it still worked after some interfaces added into device, such as MobileHotspot,VPN or other fancy virtual adapters.
I know this may be kicking a dead horse, but maybe this can help someone. I have looked all over the place for a way to find my local IP address, but everywhere I find it says to use:
Dns.GetHostEntry(Dns.GetHostName());
I don't like this at all because it just gets all the addresses assigned to your computer. If you have multiple network interfaces (which pretty much all computers do now-a-days) you have no idea which address goes with which network interface. After doing a bunch of research I created a function to use the NetworkInterface class and yank the information out of it. This way I can tell what type of interface it is (Ethernet, wireless, loopback, tunnel, etc.), whether it is active or not, and SOOO much more.
public string GetLocalIPv4(NetworkInterfaceType _type)
{
string output = "";
foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces())
{
if (item.NetworkInterfaceType == _type && item.OperationalStatus == OperationalStatus.Up)
{
foreach (UnicastIPAddressInformation ip in item.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
{
output = ip.Address.ToString();
}
}
}
}
return output;
}
Now to get the IPv4 address of your Ethernet network interface call:
GetLocalIPv4(NetworkInterfaceType.Ethernet);
Or your Wireless interface:
GetLocalIPv4(NetworkInterfaceType.Wireless80211);
If you try to get an IPv4 address for a wireless interface, but your computer doesn't have a wireless card installed it will just return an empty string. Same thing with the Ethernet interface.
Hope this helps someone! :-)
EDIT:
It was pointed out (thanks @NasBanov) that even though this function goes about extracting the IP address in a much better way than using Dns.GetHostEntry(Dns.GetHostName())
it doesn't do very well at supporting multiple interfaces of the same type or multiple IP addresses on a single interface. It will only return a single IP address when there may be multiple addresses assigned. To return ALL of these assigned addresses you could simply manipulate the original function to always return an array instead of a single string. For example:
public static string[] GetAllLocalIPv4(NetworkInterfaceType _type)
{
List<string> ipAddrList = new List<string>();
foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces())
{
if (item.NetworkInterfaceType == _type && item.OperationalStatus == OperationalStatus.Up)
{
foreach (UnicastIPAddressInformation ip in item.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
{
ipAddrList.Add(ip.Address.ToString());
}
}
}
}
return ipAddrList.ToArray();
}
Now this function will return ALL assigned addresses for a specific interface type. Now to get just a single string, you could use the .FirstOrDefault()
extension to return the first item in the array or, if it's empty, return an empty string.
GetLocalIPv4(NetworkInterfaceType.Ethernet).FirstOrDefault();
Keep in mind, in the general case you could have multiple NAT translations going on, and multiple dns servers, each operating on different NAT translation levels.
What if you have carrier grade NAT, and want to communicate with other customers of the same carrier? In the general case you never know for sure because you might appear with different host names at every NAT translation.
public static string DisplayIPAddresses()
{
string returnAddress = String.Empty;
// Get a list of all network interfaces (usually one per network card, dialup, and VPN connection)
NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface network in networkInterfaces)
{
// Read the IP configuration for each network
IPInterfaceProperties properties = network.GetIPProperties();
if (network.NetworkInterfaceType == NetworkInterfaceType.Ethernet &&
network.OperationalStatus == OperationalStatus.Up &&
!network.Description.ToLower().Contains("virtual") &&
!network.Description.ToLower().Contains("pseudo"))
{
// Each network interface may have multiple IP addresses
foreach (IPAddressInformation address in properties.UnicastAddresses)
{
// We're only interested in IPv4 addresses for now
if (address.Address.AddressFamily != AddressFamily.InterNetwork)
continue;
// Ignore loopback addresses (e.g., 127.0.0.1)
if (IPAddress.IsLoopback(address.Address))
continue;
returnAddress = address.Address.ToString();
Console.WriteLine(address.Address.ToString() + " (" + network.Name + " - " + network.Description + ")");
}
}
}
return returnAddress;
}
Other way to get IP using linq expression:
public static List<string> GetAllLocalIPv4(NetworkInterfaceType type)
{
return NetworkInterface.GetAllNetworkInterfaces()
.Where(x => x.NetworkInterfaceType == type && x.OperationalStatus == OperationalStatus.Up)
.SelectMany(x => x.GetIPProperties().UnicastAddresses)
.Where(x => x.Address.AddressFamily == AddressFamily.InterNetwork)
.Select(x => x.Address.ToString())
.ToList();
}
To get local Ip Address:
public static string GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
throw new Exception("No network adapters with an IPv4 address in the system!");
}
To check if you're connected or not:
System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();