using System;
|
using System.Collections.Generic;
|
using System.Text;
|
using System.Net.Sockets;
|
using System.Net;
|
|
namespace Common.NetWork
|
{
|
public class TcpIP
|
{
|
/// <summary>
|
/// ipæèA¢gp|[gÌæ¾
|
/// (1024`65535)
|
/// </summary>
|
/// <param name="ip4"></param>
|
/// <returns>0:澸s</returns>
|
public static int GetFreePort(string ip4)
|
{
|
for (int i = 1024; i < 65535; i++)
|
{
|
if (IsFreePort(ip4, i)) { return i; }
|
}
|
return 0;
|
}
|
|
/// <summary>
|
/// wèµ½|[gÍgpÂ\©Ç¤©
|
/// </summary>
|
/// <param name="ip4"></param>
|
/// <param name="port"></param>
|
/// <returns></returns>
|
public static bool IsFreePort(string ip4, int port)
|
{
|
using (TcpClient tc = new TcpClient())
|
{
|
try
|
{
|
tc.Connect(ip4, port);
|
return true;
|
}
|
catch (Exception e)
|
{
|
System.Diagnostics.Debug.WriteLine(e.Message);
|
}
|
}
|
return false;
|
}
|
|
/// <summary> ©ªIPÌæ¾
|
/// </summary>
|
/// <returns></returns>
|
public static List<string> GetLocalIpv4()
|
{
|
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
|
List<string> IpCollection = new List<string>();
|
foreach (IPAddress ip in localIPs)
|
{
|
if (ip.AddressFamily == AddressFamily.InterNetwork) { IpCollection.Add(ip.ToString()); }
|
}
|
return IpCollection;
|
}
|
|
/// <summary> ©ªIPÌæ¾
|
/// </summary>
|
/// <returns></returns>
|
public static string GetFirstLocalIpv4()
|
{
|
//192.168.DæIII
|
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
|
SortedList<string, string> IpCollection = new SortedList<string, string>();
|
foreach (IPAddress ip in localIPs)
|
{
|
if (ip.AddressFamily == AddressFamily.InterNetwork) { IpCollection.Add(string.Format("{0}-{1}", ip.ToString().StartsWith("192") ? "0" : "1", ip.ToString()), ip.ToString()); }
|
}
|
return IpCollection.Count == 0 ? string.Empty : IpCollection.Values[0];
|
}
|
|
/// <summary> ©ªIPÌæ¾
|
/// </summary>
|
/// <returns></returns>
|
public static IPAddress GetFirstLocalIp4Address()
|
{
|
//192.168.DæIII
|
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
|
SortedList<string, IPAddress> IpCollection = new SortedList<string, IPAddress>();
|
foreach (IPAddress ip in localIPs)
|
{
|
if (ip.AddressFamily == AddressFamily.InterNetwork) { IpCollection.Add(string.Format("{0}-{1}", ip.ToString().StartsWith("192") ? "0" : "1", ip.ToString()), ip); }
|
}
|
return IpCollection.Count == 0 ? null : IpCollection.Values[0];
|
}
|
}
|
}
|