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?
InetSocketAddress(String hostname, int port) : Creates a socketaddress object and binds it to specified port and host. Resolution of hostname is performed to find the IP address and that is used for binding purpose, not the host name. If the resolution returns null, the address will be flagged as unresolved.
public InetSocketAddress(int port) Creates a socket address where the IP address is the wildcard address and the port number a specified value. A valid port value is between 0 and 65535. A port number of zero will let the system pick up an ephemeral port in a bind operation.
Class InetAddress. This class represents an Internet Protocol (IP) address. An IP address is either a 32-bit or 128-bit unsigned number used by IP, a lower-level protocol on which protocols like UDP and TCP are built.
Class SocketAddress As an abstract class, it is meant to be subclassed with a specific, protocol dependent, implementation. It provides an immutable object used by sockets for binding, connecting, or as returned values. Since: 1.4 See Also: Socket , ServerSocket , Serialized Form.
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??
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With