从字符串创建IPEndpoint最好的方法 [英] Best way to create IPEndpoint from string

查看:149
本文介绍了从字符串创建IPEndpoint最好的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于IPEndpoint包含输出ToString方法:

Since IPEndpoint contains a ToString method that outputs:

10.10.10.10:1010

10.10.10.10:1010

应该有一个Parse&安培;的TryParse方法但没有

There should be a Parse & TryParse method but there isn't.

我可以分割的字符串':'和解析一个IP地址和一个端口

I can split the string on the ':' and parse a IP address and a port.

但有一个更优雅的方式?

But is there a more elegant way?

推荐答案

这是一个解决方案...

This is one solution...

public static IPEndPoint CreateIPEndPoint(string endPoint)
{
    string[] ep = endPoint.Split(':');
    if(ep.Length != 2) throw new FormatException("Invalid endpoint format");
    IPAddress ip;
    if(!IPAddress.TryParse(ep[0], out ip))
    {
        throw new FormatException("Invalid ip-adress");
    }
    int port;
    if(!int.TryParse(ep[1], NumberStyles.None, NumberFormatInfo.CurrentInfo, out port))
    {
        throw new FormatException("Invalid port");
    }
    return new IPEndPoint(ip, port);
}

修改:增加了一个版本,将处理IPv4和IPv6的previous人们只处理IPv4的

// Handles IPv4 and IPv6 notation.
public static IPEndPoint CreateIPEndPoint(string endPoint)
{
    string[] ep = endPoint.Split(':');
    if (ep.Length < 2) throw new FormatException("Invalid endpoint format");
    IPAddress ip;
    if (ep.Length > 2)
    {
        if (!IPAddress.TryParse(string.Join(":", ep, 0, ep.Length - 1), out ip))
        {
            throw new FormatException("Invalid ip-adress");
        }
    }
    else
    {
        if (!IPAddress.TryParse(ep[0], out ip))
        {
            throw new FormatException("Invalid ip-adress");
        }
    }
    int port;
    if (!int.TryParse(ep[ep.Length - 1], NumberStyles.None, NumberFormatInfo.CurrentInfo, out port))
    {
        throw new FormatException("Invalid port");
    }
    return new IPEndPoint(ip, port);
}

这篇关于从字符串创建IPEndpoint最好的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆