判断一个字符串如果没有端口的话,利用IPAddress.TryParse很好判断,那么有端口怎么判断呢,正则表达式?还是其他方式?

关键代码:

        /// <summary>
        /// 判断是否是合法的IP4,IP6地址
        /// </summary>
        /// <param name="ip">需要判断的字符串</param>
        /// <returns>合法则返回host部分,若不合法则返回空</returns>
        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);

        }

测试结果:

希望有所帮助!

[C#]判断是否是合法的IP4,IP6地址的更多相关文章

  1. C#检查字符串是否是合法的HTTP URL地址的代码

    在研发过程,把开发过程较好的一些内容片段记录起来,下面的内容是关于C#检查字符串是否是合法的HTTP URL地址的内容,应该是对各位有较大用处. protected string HTTPChecke ...

  2. python学习-判断是否是私网IP地址

    判断是否是私网IP地址 私网IP地址范围如下: 192.168.0.0-192.168.255.255 172.16.0.0-172.31.255.255 10.0.0.0-10.255.255.25 ...

  3. c#判断是否为合法的email地址

    题目要求: class Program { static void Main(string[] args) { Console.WriteLine("请输入正确的邮箱地址,以 @sina.c ...

  4. 判断是否是合法的IP地址

    ipv4 import re #简单的匹配给定的字符串是否是ip地址,下面的例子它不是IPv4的地址,但是它满足正则表达式 if re.match(r"^(?:[0-9]{1,3}\.){3 ...

  5. Asp.net中的一个判断session是否合法的做法

    1 if (Session["UserID"] == "" || Session["UserID"] == null) 2 { 3     ...

  6. 判断是否是有效的IPV4地址

    参考链接: https://blogs.msdn.microsoft.com/oldnewthing/20060522-08/?p=31113 http://www.cnblogs.com/txw19 ...

  7. 解决ios开发中不合法的网络请求地址

    NSString *const kWebsite = @"http://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct ...

  8. js判断非127开头的IP地址

    js验证回送地址,IP地址不能以127开头 回送地址(127.x.x.x)是本机回送地址(Loopback Address) var ipNotStartWith127 = function(ip) ...

  9. Solidity的地址 数组如何判断是否包含一个给定的地址?

    Q: given address[] wallets. What is the correct method to check that the list contains a given addre ...

随机推荐

  1. ios开发——实用技术篇Swift&Swift调用C、C++、Object

    Swift调用C.C++.Object 1.Swift调用C语言a,首先在项目中添加 CFile 文件命名为CHello,同时产生桥梁文件. b,创建之后的项目结构 b,在CHello.h文件中编写接 ...

  2. 会话跟踪session cookie

    会话跟踪 会话(Session)跟踪是Web程序中常用的技术,用来跟踪用户的整个会话.常用的会话跟踪技术Cookie与Session.Cookie通过在客户端记录信息确定用户身份,Session通过在 ...

  3. insert erase和replace的例子

    9.43 编写一个函数,接受三个string参数s.oldVal和newVal.使用迭代器及insert和erase函数将s中所有oldval替换为newVal.测试程序,用它替换通用的简写形式,如, ...

  4. [JavaScript]JS对select动态options操作[IE&FireFox兼容]

    <select id="ddlResourceType" onchange="getvalue(this)"></select>     ...

  5. 信号之abort函数

    abort函数的功能是使异常程序终止. #include <stdlib.h> void abort(void); 此函数不返回 此函数将SIGABRT信号发送给调用进程(进程不应忽略此信 ...

  6. 解决FLASH最高层的问题,让FLASH置于div之下

    三个步骤:1.设置div 的 z-index:9999 //在最上面显示 这一步就可以保证div在img之上2.<param name="wmode" value=" ...

  7. Understanding transient variables in Java and how they are practically used in HashMap---reference

    What is the significance of the transient keyword in Java? If you know the answer, good! you are a p ...

  8. Route Filters

    Route Filters The Controller's Middleware, represents a High-Level processing API, executed by the r ...

  9. iOS开发技巧系列---使用链式编程和Block来实现UIAlertView

    UIAlertView是iOS开发过程中最常用的控件之一,是提醒用户做出选择最主要的工具.在iOS8及后来的系统中,苹果更推荐使用UIAlertController来代替UIAlertView.所以本 ...

  10. 数据库中的DDL和DML语言

    "D:\mysql-5.6.22-winx64\bin"添加到系统环境变量path中了,然后在任意目录可访问mysql等命令,这样如登录等操作就不需要进入MySQL安装目录才好执行 ...