using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
namespace Common.NetWork
{
public class TcpIP
{
///
/// ipæèA¢gp|[gÌæ¾
/// (1024`65535)
///
///
/// 0:澸s
public static int GetFreePort(string ip4)
{
for (int i = 1024; i < 65535; i++)
{
if (IsFreePort(ip4, i)) { return i; }
}
return 0;
}
///
/// wèµ½|[gÍgpÂ\©Ç¤©
///
///
///
///
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;
}
/// ©ªIPÌæ¾
///
///
public static List GetLocalIpv4()
{
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
List IpCollection = new List();
foreach (IPAddress ip in localIPs)
{
if (ip.AddressFamily == AddressFamily.InterNetwork) { IpCollection.Add(ip.ToString()); }
}
return IpCollection;
}
/// ©ªIPÌæ¾
///
///
public static string GetFirstLocalIpv4()
{
//192.168.DæIII
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
SortedList IpCollection = new SortedList();
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];
}
/// ©ªIPÌæ¾
///
///
public static IPAddress GetFirstLocalIp4Address()
{
//192.168.DæIII
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
SortedList IpCollection = new SortedList();
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];
}
}
}