using System.Collections; using System.Net; using System.Net.NetworkInformation;
using System.Net.Sockets; namespace Core.Util { /// <summary> /// Ip Address help class  /// 
</summary> public class IpHelper { #region  External interface  /// <summary> ///  Get local IP address  /// 
</summary> /// <returns></returns> 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() : ""; } /// <summary> ///  Gets the first available port number  /// 
</summary> /// <returns></returns> public static int GetFirstAvailablePort() { 
int BEGIN_PORT = 1024;// Start detection from this port  int MAX_PORT = 65535; // system tcp/udp The maximum number of ports is 65535 
for (int i = BEGIN_PORT; i < MAX_PORT; i++) { if (PortIsAvailable(i)) return i; 
} return -1; } /// <summary> ///  Check whether the specified port is used  /// </summary> /// <param 
name="port"></param> /// <returns></returns> public static bool PortIsAvailable(
int port) { bool isAvailable = true; IList portUsed = PortIsUsed(); foreach (int
 pin portUsed) { if (p == port) { isAvailable = false; break; } } return 
isAvailable; } #endregion #region  Private members  /// <summary> ///  Gets the port number used by the operating system  /// 
</summary> /// <returns></returns> private static IList PortIsUsed() { 
// Get information about the local computer's network connection and communication statistics  IPGlobalProperties ipGlobalProperties = 
IPGlobalProperties.GetIPGlobalProperties(); // Returns all Tcp Listener  IPEndPoint[] 
ipsTCP= ipGlobalProperties.GetActiveTcpListeners(); // Returns all UDP Listener  
IPEndPoint[] ipsUDP = ipGlobalProperties.GetActiveUdpListeners(); 
// Returns the Internet Protocol version 4(IPV4  Transmission control protocol (TCP) Connected information . 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 } } 
Technology