//获取本机IP
void GetAddressIP()
{
///获取本地的IP地址
string AddressIP = string.Empty;
foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
{
if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
{
AddressIP = _IPAddress.ToString();
}
}
txtLocalIP.Text = AddressIP;
}
//获取端口号
using System.Net.NetworkInformation;
private const string PortReleaseGuid = "8875BD8E-4D5B-11DE-B2F4-691756D89593";
public void FindNextAvailableUDPPort(int startPort)
{
port = startPort;
bool isAvailable = true;
var mutex = new Mutex(false,
string.Concat("Global/", PortReleaseGuid));
mutex.WaitOne();
try
{
IPGlobalProperties ipGlobalProperties =
IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] endPoints =
ipGlobalProperties.GetActiveUdpListeners();
do
{
if (!isAvailable)
{
port++;
isAvailable = true;
}
foreach (IPEndPoint endPoint in endPoints)
{
if (endPoint.Port != port)
continue;
isAvailable = false;
break;
}
} while (!isAvailable && port < IPEndPoint.MaxPort);
if (!isAvailable)
throw new ApplicationException("Not able to find a free TCP port.");
// return port;
}
finally
{
mutex.ReleaseMutex();
}
servePORT.Text=port.ToString();
}