This repository has been archived on 2019-06-21. You can view files and clone it, but cannot push or open issues or pull requests.
PixelHub/PixelHub-Server/PixelHub/NetTools.cs

62 lines
2.0 KiB
C#

using System;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Net;
using System.Net.Sockets;
namespace SBRL.Utilities
{
public static class NetTools
{
/// <summary>
/// case-insensitively gets the IPv4 index of the network interface with the given name.
/// </summary>
/// <param name="interfaceName">The interface name to search for.</param>
/// <returns>The IPv4 index of the network interface with the given name.</returns>
public static int GetNetworkIndexByName4(string targetInterfaceName)
{
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface nic in nics)
{
Console.WriteLine("Id: {0}, Description: {1}", nic.Id, nic.Description);
if (nic.Id == targetInterfaceName)
return nic.GetIPv4Index();
}
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;
}
}
}
}
public static int GetIPv4Index(this NetworkInterface nic)
{
IPInterfaceProperties ipProps = nic.GetIPProperties();
IPv4InterfaceProperties ip4Props = ipProps.GetIPv4Properties();
return ip4Props.Index;
}
}
}