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

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.


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