Skip to content

Instantly share code, notes, and snippets.

@georgecao
Last active December 14, 2015 21:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save georgecao/5153767 to your computer and use it in GitHub Desktop.
Save georgecao/5153767 to your computer and use it in GitHub Desktop.
Creates a resolved {@link InetSocketAddress} when your hostname is actually an IP address.
/**
* Convert an IP in text format to its binary format.
*
* @param textIP literal IP
* @return byte array or null if failed.
*/
private byte[] getAddress(String textIP) {
if (IPAddressUtil.isIPv4LiteralAddress(textIP)) {
return IPAddressUtil.textToNumericFormatV4(textIP);
} else if (IPAddressUtil.isIPv6LiteralAddress(textIP)) {
return IPAddressUtil.textToNumericFormatV6(textIP);
}
return null;
}
/**
* Creates a resolved {@link InetSocketAddress} when your hostname is actually an IP address.
* We try to avoid Reverse DNS lookup when you make a call like {@link java.net.InetSocketAddress#getHostName()}.
*
* @param hostname a literal IP actually.
* @param port port number
* @return an {@link InetSocketAddress} with both hostname and address are same as hostname in different formats..
*/
public InetSocketAddress createResolved(String hostname, int port) {
if (null == hostname) {
throw new NullPointerException("Required hostname is null");
}
byte[] addr = getAddress(hostname);
if (null == addr) {
throw new NullPointerException("Converting hostname (" + hostname + ") to ip address got null.");
}
try {
InetAddress address = InetAddress.getByAddress(hostname, addr);
return new InetSocketAddress(address, port);
} catch (UnknownHostException e) {
// This should never happen when your hostname is a valid IP.
throw new IllegalArgumentException("Invalid hostname " + hostname, e);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment