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;
Refactoring Mrcheif's code to leverage Linq (ie. .Net 3.0+). .
private IPAddress LocalIPAddress()
{
if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
return null;
}
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
return host
.AddressList
.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork);
}
:)
I think using LinQ is easier:
Dns.GetHostEntry(Dns.GetHostName())
.AddressList
.First(x => x.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
.ToString()
Pre requisites: you have to add System.Data.Linq reference and refer it
using System.Linq;
string ipAddress ="";
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
ipAddress = Convert.ToString(ipHostInfo.AddressList.FirstOrDefault(address => address.AddressFamily == AddressFamily.InterNetwork));
Using these:
using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;
using System.Linq;
You can use a series of LINQ methods to grab the most preferred IP address.
public static bool IsIPv4(IPAddress ipa) => ipa.AddressFamily == AddressFamily.InterNetwork;
public static IPAddress GetMainIPv4() => NetworkInterface.GetAllNetworkInterfaces()
.Select((ni)=>ni.GetIPProperties())
.Where((ip)=> ip.GatewayAddresses.Where((ga) => IsIPv4(ga.Address)).Count() > 0)
.FirstOrDefault()?.UnicastAddresses?
.Where((ua) => IsIPv4(ua.Address))?.FirstOrDefault()?.Address;
This simply finds the first Network Interface that has an IPv4 Default Gateway, and gets the first IPv4 address on that interface. Networking stacks are designed to have only one Default Gateway, and therefore the one with a Default Gateway, is the best one.
WARNING: If you have an abnormal setup where the main adapter has more than one IPv4 Address, this will grab only the first one. (The solution to grabbing the best one in that scenario involves grabbing the Gateway IP, and checking to see which Unicast IP is in the same subnet as the Gateway IP Address, which would kill our ability to create a pretty LINQ method based solution, as well as being a LOT more code)
Here is a modified version (from compman2408's one) which worked for me:
internal static string GetLocalIPv4(NetworkInterfaceType _type)
{ // Checks your IP adress from the local network connected to a gateway. This to avoid issues with double network cards
string output = ""; // default output
foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces()) // Iterate over each network interface
{ // Find the network interface which has been provided in the arguments, break the loop if found
if (item.NetworkInterfaceType == _type && item.OperationalStatus == OperationalStatus.Up)
{ // Fetch the properties of this adapter
IPInterfaceProperties adapterProperties = item.GetIPProperties();
// Check if the gateway adress exist, if not its most likley a virtual network or smth
if (adapterProperties.GatewayAddresses.FirstOrDefault() != null)
{ // Iterate over each available unicast adresses
foreach (UnicastIPAddressInformation ip in adapterProperties.UnicastAddresses)
{ // If the IP is a local IPv4 adress
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{ // we got a match!
output = ip.Address.ToString();
break; // break the loop!!
}
}
}
}
// Check if we got a result if so break this method
if (output != "") { break; }
}
// Return results
return output;
}
You can call this method for example like:
GetLocalIPv4(NetworkInterfaceType.Ethernet);
The change: I'm retrieving the IP from an adapter which has a gateway IP assigned to it. Second change: I've added docstrings and break statement to make this method more efficient.
Imports System.Net
Imports System.Net.Sockets
Function LocalIP()
Dim strHostName = Dns.GetHostName
Dim Host = Dns.GetHostEntry(strHostName)
For Each ip In Host.AddressList
If ip.AddressFamily = AddressFamily.InterNetwork Then
txtIP.Text = ip.ToString
End If
Next
Return True
End Function
Below same action
Function LocalIP()
Dim Host As String =Dns.GetHostEntry(Dns.GetHostName).AddressList(1).MapToIPv4.ToString
txtIP.Text = Host
Return True
End Function