判断一个字符串如果没有端口的话,利用IPAddress.TryParse很好判断,那么有端口怎么判断呢,正则表达式?还是其他方式?
关键代码:
/// /// 判断是否是合法的IP4,IP6地址/// /// 需要判断的字符串/// 合法则返回host部分,若不合法则返回空 public static string GetIPAddress(string ip) { string _ipAddress = string.Empty; if (!string.IsNullOrEmpty(ip)) { UriHostNameType _hostType = Uri.CheckHostName(ip); if (_hostType == UriHostNameType.Unknown)//譬如 "192.168.1.1:8060"或者[2001:0DB8:02de::0e13]:9010 { Uri _url; if (Uri.TryCreate(string.Format("http://{0}", ip), UriKind.Absolute, out _url)) { _ipAddress = IPAddressTryParse(_url.Host); } } else if (_hostType == UriHostNameType.IPv4 || _hostType == UriHostNameType.IPv6) { _ipAddress = IPAddressTryParse(ip); } } return _ipAddress; } private static string IPAddressTryParse(string ip) { string _ipAddress = string.Empty; IPAddress _ipAdr; if (IPAddress.TryParse(ip, out _ipAdr)) { _ipAddress = _ipAdr.ToString(); } return _ipAddress; }
单元测试:
[TestMethod()]public void GetIPAddressTest(){string _ip4Address1 = "192.168.1.1";string _expected1 = "192.168.1.1"; string _actual1 = NetWorkToolV2.GetIPAddress(_ip4Address1); Assert.AreEqual(_expected1, _actual1); string _ip4Address2 = "192.168.1.1:8060"; string _expected2 = "192.168.1.1"; string _actual2 = NetWorkToolV2.GetIPAddress(_ip4Address2); Assert.AreEqual(_expected2, _actual2); string _ip6Address3 = "2001:0DB8:02de::0e13"; string _expected3 = "2001:DB8:2de::e13"; string _actual3 = NetWorkToolV2.GetIPAddress(_ip6Address3); Assert.AreEqual(_expected3, _actual3,true); string _ip6Address4 = "[2001:0DB8:2de::e13]:9010"; string _expected4 = "2001:DB8:2de::e13"; string _actual4 = NetWorkToolV2.GetIPAddress(_ip6Address4); Assert.AreEqual(_expected4, _actual4, true); string _ipAddress5 = "erroriptest"; string _expected5 = string.Empty; string _actual5 = NetWorkToolV2.GetIPAddress(_ipAddress5); Assert.AreEqual(_expected5, _actual5); }
测试结果:
希望有所帮助!