this a old thread but today I'm looking for this, but find a better answer, I think.
/// <summary>
/// Get ifIndex of ip (ip address to connect)
/// </summary>
/// <param name="ip">IP Address that want to connect</param>
/// <param name="description">Lan card description</param>
/// <param name="ifIndex">interface index</param>
/// <param name="ifAddress">IP Address of Lan Interface</param>
private static void CheckInterface(string ip, out string description, out int ifIndex, out IPAddress ifAddress)
{
description = "";
ifIndex = -1;
ifAddress = IPAddress.Any;
var myIp = IPAddress.Parse(ip);
if (!NetworkInterface.GetIsNetworkAvailable()) return;
foreach (var adapter in NetworkInterface.GetAllNetworkInterfaces())
{
if (!adapter.SupportsMulticast) continue;
if (adapter.OperationalStatus != OperationalStatus.Up) continue;
var properties = adapter.GetIPProperties();
if (!properties.MulticastAddresses.Any()) continue;
var p = properties.GetIPv4Properties();
if (p == null) continue;
foreach (var ipInfo in properties.UnicastAddresses)
{
if (ipInfo.Address.AddressFamily == AddressFamily.InterNetwork)
{
//Console.WriteLine("Address:{0} == {1}", ipInfo.Address, myIp);
var adpIp = ipInfo.Address.GetAddressBytes();
var cmpIp = myIp.GetAddressBytes();
if ((adpIp[0] == cmpIp[0]) && (adpIp[1] == cmpIp[1]) && (adpIp[2] == cmpIp[2]))
{
description = adapter.Description;
ifIndex = p.Index;
ifAddress = ipInfo.Address;
return;
//Console.WriteLine("Name {0} ifIndex {1}", adapter.Description, p.Index);
}
}
}
}
}
Today, works for me! (when ifIndex is -1, not found an interface)