(エッセンス)2020年6月26日C#クラスライブラリIpアドレスヘルプクラス
15230 ワード
using System.Collections;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
namespace Core.Util
{
///
/// Ip
///
public class IpHelper
{
#region
///
/// IP
///
///
public static string GetLocalIp()
{
UnicastIPAddressInformation mostSuitableIp = null;
var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (var network in networkInterfaces)
{
if (network.OperationalStatus != OperationalStatus.Up)
continue;
var properties = network.GetIPProperties();
if (properties.GatewayAddresses.Count == 0)
continue;
foreach (var address in properties.UnicastAddresses)
{
if (address.Address.AddressFamily != AddressFamily.InterNetwork)
continue;
if (IPAddress.IsLoopback(address.Address))
continue;
return address.Address.ToString();
}
}
return mostSuitableIp != null
? mostSuitableIp.Address.ToString()
: "";
}
///
///
///
///
public static int GetFirstAvailablePort()
{
int BEGIN_PORT = 1024;//
int MAX_PORT = 65535; // tcp/udp 65535
for (int i = BEGIN_PORT; i < MAX_PORT; i++)
{
if (PortIsAvailable(i)) return i;
}
return -1;
}
///
///
///
///
///
public static bool PortIsAvailable(int port)
{
bool isAvailable = true;
IList portUsed = PortIsUsed();
foreach (int p in portUsed)
{
if (p == port)
{
isAvailable = false; break;
}
}
return isAvailable;
}
#endregion
#region
///
///
///
///
private static IList PortIsUsed()
{
//
IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
// Tcp
IPEndPoint[] ipsTCP = ipGlobalProperties.GetActiveTcpListeners();
// UDP
IPEndPoint[] ipsUDP = ipGlobalProperties.GetActiveUdpListeners();
// Internet 4(IPV4 (TCP) 。
TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();
IList allPorts = new ArrayList();
foreach (IPEndPoint ep in ipsTCP) allPorts.Add(ep.Port);
foreach (IPEndPoint ep in ipsUDP) allPorts.Add(ep.Port);
foreach (TcpConnectionInformation conn in tcpConnInfoArray) allPorts.Add(conn.LocalEndPoint.Port);
return allPorts;
}
#endregion
}
}