using System; using System.Collections.Generic; using System.Text; using System.Net.Sockets; using System.Net; namespace Common.NetWork { public class TcpIP { /// /// ip‚æ‚èA–¢Žg—pƒ|[ƒ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‚ÍŽg—p‰Â”\‚©‚Ç‚¤‚© /// /// /// /// 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æIII 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æIII 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]; } } }