Open msalai opened 6 years ago
This does the job:
/// This thing below will return any virtual NIC before the real nic without twitching....
/// It does not work and does not return the real NIC of the computer
/// Very naif...
/// I have modified it to at least compare the IP with the IP linked to the gateway in the local machine.
/// </summary>
/// <returns></returns>
private static NetworkInterface GetNetworkInterface()
{
var computerProperties = IPGlobalProperties.GetIPGlobalProperties();
if (computerProperties == null)
return null;
var localIP = getRealNetworkInterfaceIPAddress();
var nics = NetworkInterface.GetAllNetworkInterfaces();
if (nics == null || nics.Length < 1)
return null;
NetworkInterface best = null;
foreach (NetworkInterface adapter in nics)
{
if (adapter.NetworkInterfaceType == NetworkInterfaceType.Loopback || adapter.NetworkInterfaceType == NetworkInterfaceType.Unknown)
continue;
if (!adapter.Supports(NetworkInterfaceComponent.IPv4))
continue;
if (best == null)
best = adapter;
if (adapter.OperationalStatus != OperationalStatus.Up)
continue;
// make sure this adapter has any ipv4 addresses
IPInterfaceProperties properties = adapter.GetIPProperties();
foreach (UnicastIPAddressInformation unicastAddress in properties.UnicastAddresses)
{
if (unicastAddress != null && unicastAddress.Address != null && unicastAddress.Address.AddressFamily == AddressFamily.InterNetwork
&& unicastAddress.Address.Equals(localIP))
{
// Yes it does, return this network interface.
return adapter;
}
}
}
return best;
}
private static IPAddress getRealNetworkInterfaceIPAddress()
{
IPAddress localIP = null;
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
{
socket.Connect("8.8.8.8", 65530);
IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
localIP = endPoint.Address;
}
return localIP;
}```
However, still the 'best' is wasp ready to sting any time...
I have issue with this library when there are multiple network interface cards. Discovery fails completely. In my case, virtual cards were present from VMWare software.
Have anyone experienced similar problem? Any fix out there?