简体   繁体   English

使用任何主机的 IP 地址构造 InetSocketAddress 的正确方法是什么?

[英]What is the correct way to construct InetSocketAddress with any host an IP address?

I want to create an InetSocketAddress but I want to do it right no matter if I get a host:port or a ip:port.我想创建一个 InetSocketAddress,但无论我得到一个主机:端口还是一个 ip:端口,我都想正确地做。 I see it has two constructors, one for host (String) and another one for IP (InetAddress).我看到它有两个构造函数,一个用于主机(字符串),另一个用于 IP(InetAddress)。 Do I have to determine myself if I got an IP or HOST in order to choose between these two constructors?为了在这两个构造函数之间进行选择,我是否必须自己确定是否获得了 IP 或 HOST? Am I missing something here?我在这里错过了什么吗?

You can infer from the Javadoc, and see in the source code, that new InetSocketAddress(String hostname, int port) calls InetAddress.getByName(hostname) , which sorts all that out for you as documented.您可以从 Javadoc 推断,并在源代码中看到, new InetSocketAddress(String hostname, int port)调用InetAddress.getByName(hostname) ,它按照文档为您整理了所有内容。

So the problem you're posting about doesn't really exist.因此,您发布的问题实际上并不存在。 Just pass whatever string you get, whether host name or IP address.只需传递您获得的任何字符串,无论是主机名还是 IP 地址。

I'm not entirely sure what it is your asking, but, I did this quick test on my PC without any issue我不完全确定你问的是什么,但是,我在我的电脑上做了这个快速测试,没有任何问题

try {

    String ipAddress = ""; // Add your own
    String hostName = ""; // Add your own

    int port = ...; // You'll need some sort of service to connect to


    InetSocketAddress byAddress1 = new InetSocketAddress(ipAddress, port);
    InetSocketAddress byAddress2 = new InetSocketAddress(InetAddress.getByName(ipAddress), port);

    InetSocketAddress byName1 = new InetSocketAddress(hostName, port);
    InetSocketAddress byName2 = new InetSocketAddress(InetAddress.getByName(hostName), port);

} catch (UnknownHostException unknownHostException) {
    unknownHostException.printStackTrace();
}

The bigger question is, what are expected to get as input?更大的问题是,期望得到什么作为输入? IP address, host name or some other form?? IP 地址、主机名或其他形式?

You will have to determine whether the String passed to the constructor is an IP or a Host name.您必须确定传递给构造函数的字符串是 IP 还是主机名。 I'd do it with a Regex for the IP address.我会使用正则表达式作为 IP 地址。 If that fails, it's probably a host name.如果失败,则可能是主机名。

Both IP addresses and Host names are String, so you will how only one constructor. IP 地址和主机名都是 String,因此您将如何只有一个构造函数。

Also it is worth to mention, if you don't know your dns name or ip , you can simple use constructor with port only.另外值得一提的是,如果您不知道您的dns名称或ip ,您可以简单地使用仅带有端口的构造函数。

new InetSocketAddress(8080)

it internally invokes InetAddress.anyLocalAddress()它在内部调用InetAddress.anyLocalAddress()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM