Java:验证和转换“host:port”的常用方法到InetSocketAddress? [英] Java: Common way to validate and convert "host:port" to InetSocketAddress?

查看:432
本文介绍了Java:验证和转换“host:port”的常用方法到InetSocketAddress?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java中用于验证和转换 host 形式的字符串到 InetSocketAddress

What is the common way in Java to validate and convert a string of the form host:port into an instance of InetSocketAddress?

如果满足以下条件会很好:

It would be nice if following criteria were met:


  • 无地址查找;

  • No address lookups;

适用于IPv4,IPv6和字符串主机名;

(适用于IPv4是 ip:port ,对于IPv6,它是 [ip]:port ,对吗?是否有一些RFC定义了所有这些方案?)

Working for IPv4, IPv6, and "string" hostnames;
(For IPv4 it's ip:port, for IPv6 it's [ip]:port, right? Is there some RFC which defines all these schemes?)

优先不用手工解析字符串。

(我在考虑所有这些特殊情况,当有人认为他知道套接字地址的所有有效形式,但忘记特殊情况会导致意外结果。)

Preferable without parsing the string by hand.
(I'm thinking about all those special cases, when someone think he knows all valid forms of socket addresses, but forgets about "that special case" which leads to unexpected results.)

推荐答案

我自己提出了一种可行的解决方法。

I myself propose one possible workaround solution.

将字符串转换为URI(这将自动验证它),然后查询URI的h ost和端口组件。

Convert a string into URI (this would validate it automatically) and then query the URI's host and port components.

遗憾的是,带有主机组件的URI必须有一个方案。这就是为什么这个解决方案不完美。

Sadly, an URI with a host component MUST have a scheme. This is why this solution is "not perfect".

String string = ... // some string which has to be validated

try {
  // WORKAROUND: add any scheme to make the resulting URI valid.
  URI uri = new URI("my://" + string); // may throw URISyntaxException
  String host = uri.getHost();
  int port = uri.getPort();

  if (uri.getHost() == null || uri.getPort() == -1) {
    throw new URISyntaxException(uri.toString(),
      "URI must have host and port parts");
  }

  // here, additional checks can be performed, such as
  // presence of path, query, fragment, ...


  // validation succeeded
  return new InetSocketAddress (host, port);

} catch (URISyntaxException ex) {
  // validation failed
}

此解决方案无需自定义字符串解析,适用于 IPv4 1.1.1.1:123 ), IPv6 [:: 0]:123 )和主机名 my.host.com:123 )。

This solution needs no custom string parsing, works with IPv4 (1.1.1.1:123), IPv6 ([::0]:123) and host names (my.host.com:123).

无意中,此解决方案非常适合我的场景。无论如何我还是要使用URI方案。

这篇关于Java:验证和转换“host:port”的常用方法到InetSocketAddress?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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