Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import java.io.Serializable;
import java.net.InetAddress;
import java.net.UnknownHostException;
public final class InetAddressAndPort implements Serializable {
private static final long serialVersionUID = 0;
static volatile int defaultPort = 7000;
private final InetAddress address;
private final int port;
public InetAddressAndPort() throws UnknownHostException {
this.address = InetAddress.getLocalHost();
this.port = defaultPort;
}
private InetAddressAndPort(InetAddress address, int port) {
validatePortRange(port);
this.address = address;
this.port = port;
}
public static InetAddressAndPort getByAddress(InetAddress address){
return getByAddressOverrideDefaults(address, null);
}
public static InetAddressAndPort getByAddressOverrideDefaults(InetAddress address, Integer port) {
if (port == null) {
port = defaultPort;
}
return new InetAddressAndPort(address, port);
}
public InetAddressAndPort withPort(int port) {
return new InetAddressAndPort(address, port);
}
private static void validatePortRange(int port) {
if (port < 0 | port > 65535)
{
throw new IllegalArgumentException("Port " + port + " is not a valid port number in the range 0-65535");
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
InetAddressAndPort that = (InetAddressAndPort) o;
if (port != that.port) return false;
return address.equals(that.address);
}
@Override
public int hashCode(){
int result = address.hashCode();
result = 31 * result + port;
return result;
}
public String getHostAddress(boolean withPort) {
if (withPort)
return toString();
else
return address.getHostAddress();
}
@Override
public String toString()
{
return toString(true);
}
public String toString(boolean withPort) {
if (withPort)
return toString(address, port);
else
return address.toString();
}
public static String toString(InetAddress address, int port) {
return address.getHostAddress() + ":" + port;
}
public static String getLocalHost() throws UnknownHostException {
return InetAddress.getLocalHost().getHostAddress();
}
public static void initializeDefaultPort(int port) {
defaultPort = port;
}
static int getDefaultPort() {
return defaultPort;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.