using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; namespace FastGithub.Configuration { /// /// 提供本机设备信息 /// public static class LocalMachine { /// /// 获取设备名 /// public static string Name => Environment.MachineName; /// /// 获取本机设备所有IP /// /// public static IEnumerable GetAllIPAddresses() { yield return IPAddress.Loopback; yield return IPAddress.IPv6Loopback; foreach (var @interface in NetworkInterface.GetAllNetworkInterfaces()) { foreach (var addressInfo in @interface.GetIPProperties().UnicastAddresses) { yield return addressInfo.Address; } } } /// /// 获取本机设备所有IPv4 /// /// public static IEnumerable GetAllIPv4Addresses() { foreach (var address in GetAllIPAddresses()) { if (address.AddressFamily == AddressFamily.InterNetwork) { yield return address; } } } /// /// 返回本机设备是否包含指定IP /// /// /// public static bool ContainsIPAddress(IPAddress address) { return GetAllIPAddresses().Contains(address); } /// /// 获取与远程节点通讯的的本机IP地址 /// /// 远程地址 /// public static IPAddress? GetLocalIPAddress(EndPoint remoteEndPoint) { try { using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); socket.Connect(remoteEndPoint); return socket.LocalEndPoint is IPEndPoint localEndPoint ? localEndPoint.Address : default; } catch (Exception) { return default; } } /// /// 获取可用的随机端口 /// /// /// 最小值 /// public static int GetAvailablePort(AddressFamily addressFamily, int min = 1025) { var hashSet = new HashSet(); var tcpListeners = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners(); var udpListeners = IPGlobalProperties.GetIPGlobalProperties().GetActiveUdpListeners(); foreach (var item in tcpListeners) { if (item.AddressFamily == addressFamily) { hashSet.Add(item.Port); } } foreach (var item in udpListeners) { if (item.AddressFamily == addressFamily) { hashSet.Add(item.Port); } } for (var port = min; port < ushort.MaxValue; port++) { if (hashSet.Contains(port) == false) { return port; } } throw new FastGithubException("当前无可用的端口"); } /// /// 是否可以监听指定tcp端口 /// /// /// public static bool CanListenTcp(int port) { var tcpListeners = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners(); return tcpListeners.Any(item => item.Port == port) == false; } /// /// 是否可以监听指定udp端口 /// /// /// public static bool CanListenUdp(int port) { var udpListeners = IPGlobalProperties.GetIPGlobalProperties().GetActiveUdpListeners(); return udpListeners.Any(item => item.Port == port) == false; } } }