Last active
December 14, 2015 21:49
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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