using System; using System.Diagnostics; using System.Net; using System.Net.Sockets; using System.Text.RegularExpressions; namespace LJLib.IP { public static class IPUtils { [Obsolete("建议改用方法GetURLIPv4")] public static string GetURLIP(string URL) { string ip = string.Empty; try { IPHostEntry ipHost = Dns.GetHostEntry(URL); bool haveip = false; for (int i = 0; i < ipHost.AddressList.Length; i++) { if (!haveip) { var tip = ipHost.AddressList[i].ToString(); if (tip != "::1") { ip = tip; haveip = true; } } } } catch (System.Exception ex) { Debug.Write(string.Format("获取龙嘉网失败,URL:[{0}],{1}.", URL, ex.ToString())); ip = "获取龙嘉网失败:" + URL; } return ip; } /// /// 返回URL的IPv4的地址 /// /// URL地址 /// IPv4 public static IPAddress GetURLIPv4(string URL) { IPAddress ip = null; if (IsIPv4Address(URL)) { return IPAddress.Parse(URL); } try { var ipHost = Dns.GetHostEntry(URL); foreach (var ipAddress in ipHost.AddressList) { if (ipAddress.AddressFamily == AddressFamily.InterNetwork) { if (!IPAddress.IsLoopback(ipAddress)) { return ipAddress; } ip = ipAddress; } } } catch (Exception ex) { Debug.Write(string.Format("获取龙嘉网失败,URL:[{0}],{1}.", URL, ex.ToString())); } return ip; } public static IPEndPoint GetIPEndPoint(string ipPortStr) { int index = ipPortStr.IndexOf(":"); if (index < 0) { throw new Exception(string.Format("ip:port不合法,{0}", ipPortStr)); } var ipStr = ipPortStr.Substring(0, index); var portStr = ipPortStr.Substring(index + 1); try { var address = IPAddress.Parse(ipStr); var port = int.Parse(portStr); return new IPEndPoint(address, port); } catch (Exception ex) { throw new Exception(string.Format("ip:port不合法,{0},异常:{1}", ipPortStr, ex)); } } private static Regex r = null; public static bool IsIPv4Address(string ip) { if (r == null) { r = new Regex(@"^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$"); } return r.IsMatch(ip); } /// /// 判断TcpClient是否在连接 /// public static bool IsConnecting(TcpClient tcpclient) { try { if (!tcpclient.Connected) { return false; } var ifSelectRead = tcpclient.Client.Poll(1000, SelectMode.SelectRead); if (!ifSelectRead) // 网络在连接无数据可读 { return true; } var ns = tcpclient.GetStream(); return ns.CanRead && ns.DataAvailable; } catch (Exception ex) { if (!(ex is ObjectDisposedException) && !(ex is InvalidOperationException)) { Trace.Write(ex.ToString()); } return false; } } } }