JohnPristine
JohnPristine

Reputation: 3575

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. I see it has two constructors, one for host (String) and another one for IP (InetAddress). Do I have to determine myself if I got an IP or HOST in order to choose between these two constructors? Am I missing something here?

Upvotes: 13

Views: 43069

Answers (4)

Alex
Alex

Reputation: 4413

Also it is worth to mention, if you don't know your dns name or ip, you can simple use constructor with port only.

new InetSocketAddress(8080)

it internally invokes InetAddress.anyLocalAddress()

Upvotes: 0

user207421
user207421

Reputation: 311028

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.

So the problem you're posting about doesn't really exist. Just pass whatever string you get, whether host name or IP address.

Upvotes: 19

ksnortum
ksnortum

Reputation: 3057

You will have to determine whether the String passed to the constructor is an IP or a Host name. I'd do it with a Regex for the IP address. If that fails, it's probably a host name.

Both IP addresses and Host names are String, so you will how only one constructor.

Upvotes: 0

MadProgrammer
MadProgrammer

Reputation: 347334

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??

Upvotes: 3

Related Questions