Write extra network interface finding method

This commit is contained in:
Starbeamrainbowlabs 2016-10-24 21:30:51 +01:00
parent 9d141b2682
commit e135e4e8d7
1 changed files with 27 additions and 0 deletions

View File

@ -1,6 +1,8 @@
using System; using System;
using System.Net.NetworkInformation; using System.Net.NetworkInformation;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Net;
using System.Net.Sockets;
namespace SBRL.Utilities namespace SBRL.Utilities
{ {
@ -24,6 +26,31 @@ namespace SBRL.Utilities
} }
throw new Exception($"Error: Can't find network interface with the name {targetInterfaceName}."); throw new Exception($"Error: Can't find network interface with the name {targetInterfaceName}.");
} }
/// <summary>
/// Gets the NetworkInterface with the given IP address.
/// </summary>
/// <param name="targetIP">The target IP to search for.</param>
/// <returns>The network index with the given IP address.</returns>
public static int GetNetworkIndexByIP(IPAddress targetIP)
{
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
foreach(NetworkInterface nic in nics)
{
IPInterfaceProperties ipProps = nic.GetIPProperties();
foreach(UnicastIPAddressInformation ip in ipProps.UnicastAddresses)
{
// Only bother with external addresses
if (ip.Address.AddressFamily != AddressFamily.InterNetwork)
continue;
if (ip.Address == targetIP)
{
IPv4InterfaceProperties ip4Props = ipProps.GetIPv4Properties();
return ip4Props.Index;
}
}
}
}
} }
} }