I have multiple network cards on my computer. (Because of VMWare)
How can I find the IPv4 address of the active card. I mean if I send a ping in a terminal and intercept packet in WireShark, I want the address of "Source".
I thought of checking every network interface and look if GateWay is empty or null ? Or maybe ping 127.0.0.1 and get the IP source of the ping request ? But cannot implement it.
For now I have this code which i found on StackOverFlow
public static string GetLocalIpAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
return host.AddressList.First(h => h.AddressFamily == AddressFamily.InterNetwork).ToString();
}
But it gets me the IP of the VmWare card. But I don't know what else that ".First()
" I could use.
I have finally found an efficient way of getting the real IP. Basically it looks for all interfaces in IPv4, that are UP and the thing that makes it decide, is it only takes the interface with a default gateway.
public static string GetLocalIpAddress() {
foreach(var netI in NetworkInterface.GetAllNetworkInterfaces()) {
if (netI.NetworkInterfaceType != NetworkInterfaceType.Wireless80211 &&
(netI.NetworkInterfaceType != NetworkInterfaceType.Ethernet ||
netI.OperationalStatus != OperationalStatus.Up)) continue;
foreach(var uniIpAddrInfo in netI.GetIPProperties().UnicastAddresses.Where(x => netI.GetIPProperties().GatewayAddresses.Count > 0)) {
if (uniIpAddrInfo.Address.AddressFamily == AddressFamily.InterNetwork &&
uniIpAddrInfo.AddressPreferredLifetime != uint.MaxValue)
return uniIpAddrInfo.Address.ToString();
}
}
Logger.Log("You local IPv4 address couldn't be found...");
return null;
}
Edit 5 years later : In the mean time I have found a better way of getting the local IP address. You basically make a DNS request to Google's DNS server (or anything else) and see what is the source IP that is picked up by your PC.
public static string GetLocalIp() {
using(var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0)) {
socket.Connect("8.8.8.8", 65530);
if (!(socket.LocalEndPoint is IPEndPoint endPoint) || endPoint.Address == null) {
return null;
}
return endPoint.Address.ToString();
}
}