java.net.Inet6Address Java Examples

The following examples show how to use java.net.Inet6Address. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Inet6AddressSerializationTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    // args[0] == generate-loopback generates serial data for loopback if
    // args[0] == generateAll generates serial data for interfaces with an
    // IPV6 address binding

    if (args.length != 0) {

        if (args[0].equals("generate-loopback")) {

            generateSerializedInet6AddressData(Inet6Address.getByAddress(
                    InetAddress.getLoopbackAddress().getHostName(),
                    LOOPBACKIPV6ADDRESS, LOOPBACK_SCOPE_ID), System.out,
                    true);

        } else {
            generateAllInet6AddressSerializedData();
        }
    } else {
        runTests();
    }
}
 
Example #2
Source File: JdpBroadcaster.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a new broadcaster
 *
 * @param address - multicast group address
 * @param srcAddress - address of interface we should use to broadcast.
 * @param port - udp port to use
 * @param ttl - packet ttl
 * @throws IOException
 */
public JdpBroadcaster(InetAddress address, InetAddress srcAddress, int port, int ttl)
        throws IOException, JdpException {
    this.addr = address;
    this.port = port;

    ProtocolFamily family = (address instanceof Inet6Address)
            ? StandardProtocolFamily.INET6 : StandardProtocolFamily.INET;

    channel = DatagramChannel.open(family);
    channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    channel.setOption(StandardSocketOptions.IP_MULTICAST_TTL, ttl);

    // with srcAddress equal to null, this constructor do exactly the same as
    // if srcAddress is not passed
    if (srcAddress != null) {
        // User requests particular interface to bind to
        NetworkInterface interf = NetworkInterface.getByInetAddress(srcAddress);
        try {
            channel.bind(new InetSocketAddress(srcAddress, 0));
        } catch (UnsupportedAddressTypeException ex) {
            throw new JdpException("Unable to bind to source address");
        }
        channel.setOption(StandardSocketOptions.IP_MULTICAST_IF, interf);
    }
}
 
Example #3
Source File: SessionLSPTunnelIPv6.java    From netphony-network-protocols with Apache License 2.0 6 votes vote down vote up
public void decode(byte[] bytes, int offset){
	
	byte[] receivedAddress = new byte[16];
	System.arraycopy(bytes,offset+4,receivedAddress,0,16);
	try{
		egressNodeAddress = (Inet6Address) Inet6Address.getByAddress(receivedAddress);
	}catch(UnknownHostException e){
		// FIXME: Poner logs con respecto a excepcion
	}
	offset = offset + 16;
	tunnelId = (int)(bytes[offset+2] | bytes[offset+3]);
	offset = offset + 4;
	extendedTunnelId = (int)(bytes[offset] | bytes[offset+1] | bytes[offset+2] | bytes[offset+3] | bytes[offset+4] | bytes[offset+5] | bytes[offset+6] | bytes[offset+7] | bytes[offset+8] | bytes[offset+9] | bytes[offset+10] | bytes[offset+11] | bytes[offset+12] | bytes[offset+13] | bytes[offset+14] | bytes[offset+15]);

	

}
 
Example #4
Source File: Inet6AddressSerializationTest.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    // args[0] == generate-loopback generates serial data for loopback if
    // args[0] == generateAll generates serial data for interfaces with an
    // IPV6 address binding

    if (args.length != 0) {

        if (args[0].equals("generate-loopback")) {

            generateSerializedInet6AddressData(Inet6Address.getByAddress(
                    InetAddress.getLoopbackAddress().getHostName(),
                    LOOPBACKIPV6ADDRESS, LOOPBACK_SCOPE_ID), System.out,
                    true);

        } else {
            generateAllInet6AddressSerializedData();
        }
    } else {
        runTests();
    }
}
 
Example #5
Source File: PgBulkInsertTest.java    From PgBulkInsert with MIT License 6 votes vote down vote up
@Test
public void saveAll_Inet6_Test() throws SQLException, UnknownHostException {

    // This list will be inserted.
    List<SampleEntity> entities = new ArrayList<>();

    // Create the Entity to insert:
    SampleEntity entity = new SampleEntity();
    entity.col_inet6Address = (Inet6Address) Inet6Address.getByName("1080::8:800:200c:417a");

    entities.add(entity);

    PgBulkInsert<SampleEntity> pgBulkInsert = new PgBulkInsert<>(new SampleEntityMapping());

    pgBulkInsert.saveAll(PostgreSqlUtils.getPGConnection(connection), entities.stream());

    ResultSet rs = getAll();

    while (rs.next()) {
        String v = rs.getString("col_inet6");
        Assert.assertEquals("1080::8:800:200c:417a", v);
    }
}
 
Example #6
Source File: IPUtil.java    From radar with Apache License 2.0 6 votes vote down vote up
public static String getLinuxLocalIP() {
	String ip = "";
	try {
		Enumeration<NetworkInterface> e1 = (Enumeration<NetworkInterface>) NetworkInterface.getNetworkInterfaces();
		while (e1.hasMoreElements()) {
			NetworkInterface ni = e1.nextElement();
			if ((NETWORK_CARD.equals(ni.getName())) || (NETWORK_CARD_BAND.equals(ni.getName()))) {
				Enumeration<InetAddress> e2 = ni.getInetAddresses();
				while (e2.hasMoreElements()) {
					InetAddress ia = e2.nextElement();
					if (ia instanceof Inet6Address) {
						continue;
					}
					ip = ia.getHostAddress();
				}
				break;
			} else {
				continue;
			}
		}
	} catch (SocketException e) {
		e.printStackTrace();
	}
	return ip;
}
 
Example #7
Source File: Inet6AddressSerializationTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private static byte[] getThisHostIPV6Address(String hostName)
        throws Exception {
    InetAddress[] thisHostIPAddresses = null;
    try {
        thisHostIPAddresses = InetAddress.getAllByName(InetAddress
                .getLocalHost().getHostName());
    } catch (UnknownHostException uhEx) {
        uhEx.printStackTrace();
        throw uhEx;
    }
    byte[] thisHostIPV6Address = null;
    for (InetAddress inetAddress : thisHostIPAddresses) {
        if (inetAddress instanceof Inet6Address) {
            if (inetAddress.getHostName().equals(hostName)) {
                thisHostIPV6Address = inetAddress.getAddress();
                break;
            }
        }
    }
    // System.err.println("getThisHostIPV6Address: address is "
    // + Arrays.toString(thisHostIPV6Address));
    return thisHostIPV6Address;
}
 
Example #8
Source File: Inet6AddressSerializationTest.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
static void testAllNetworkInterfaces() throws Exception {
    System.err.println("\n testAllNetworkInterfaces: \n ");
    for (Enumeration<NetworkInterface> e = NetworkInterface
            .getNetworkInterfaces(); e.hasMoreElements();) {
        NetworkInterface netIF = e.nextElement();
        for (Enumeration<InetAddress> iadrs = netIF.getInetAddresses(); iadrs
                .hasMoreElements();) {
            InetAddress iadr = iadrs.nextElement();
            if (iadr instanceof Inet6Address) {
                System.err.println("Test NetworkInterface:  " + netIF);
                Inet6Address i6adr = (Inet6Address) iadr;
                System.err.println("Testing with " + iadr);
                System.err.println(" scoped iface: "
                        + i6adr.getScopedInterface());
                testInet6AddressSerialization(i6adr, null);
            }
        }
    }
}
 
Example #9
Source File: SessionIPv6.java    From netphony-network-protocols with Apache License 2.0 6 votes vote down vote up
@Override
public void decode(byte[] bytes, int offset) {
	
	byte[] receivedAddress = new byte[16];
	
	offset = offset + RSVPObjectParameters.RSVP_OBJECT_COMMON_HEADER_SIZE;
	
	System.arraycopy(bytes,offset,receivedAddress,0,16);
	try{
		destAddress = (Inet6Address) Inet6Address.getByAddress(receivedAddress);
	}catch(UnknownHostException e){
		// FIXME: Poner logs con respecto a excepcion
	}
	offset = offset + 16;
	protocolId = bytes[offset];
	flags = bytes[offset+1];
	destPort = bytes[offset+2] | bytes[offset+3];
	
}
 
Example #10
Source File: Inet6AddressSerializationTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
static void generateAllInet6AddressSerializedData() throws IOException {
    // System.err.println("generateAllInet6AddressSerializedData: enter ....");

    List<Inet6Address> inet6Addresses;

    try {
        inet6Addresses = getAllInet6Addresses();
    } catch (Exception e) {
        e.printStackTrace();
        throw new IOException(e);
    }

    for (Inet6Address inet6Address : inet6Addresses) {
        generateSerializedInet6AddressData(inet6Address, System.out, true);
    }
}
 
Example #11
Source File: OpenVPNService.java    From EasyVPN-Free with GNU General Public License v3.0 6 votes vote down vote up
public void addRoutev6(String network, String device) {
    String[] v6parts = network.split("/");
    boolean included = isAndroidTunDevice(device);

    // Tun is opened after ROUTE6, no device name may be present

    try {
        Inet6Address ip = (Inet6Address) InetAddress.getAllByName(v6parts[0])[0];
        int mask = Integer.parseInt(v6parts[1]);
        mRoutesv6.addIPv6(ip, mask, included);

    } catch (UnknownHostException e) {
        VpnStatus.logException(e);
    }


}
 
Example #12
Source File: Inet6AddressSerializationTest.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
static byte[] generateSerializedInet6AddressData(Inet6Address addr,
        PrintStream out, boolean outputToFile) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try (ObjectOutputStream oos = new ObjectOutputStream(bos)) {
        oos.writeObject(addr);
    }

    String ifname = getIfName(addr);
    byte[] ba = bos.toByteArray();
    if (out != null) {
        out.format("static final byte[] SerialData" + ifname + " = {\n");
        for (int i = 0; i < ba.length; i++) {
            out.format(" (byte)0x%02X", ba[i]);
            if (i != (ba.length - 1))
                out.format(",");
            if (((i + 1) % 6) == 0)
                out.format("\n");
        }
        out.format(" };\n \n");
    }
    if (outputToFile) {
        serializeInet6AddressToFile(addr);
    }
    return ba;
}
 
Example #13
Source File: SocksIPv6Test.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private boolean ensureIPv6OnLoopback() throws Exception {
    boolean ipv6 = false;

    List<NetworkInterface> nics = Collections.list(NetworkInterface.getNetworkInterfaces());
    for (NetworkInterface nic : nics) {
        if (!nic.isLoopback()) {
            continue;
        }
        List<InetAddress> addrs = Collections.list(nic.getInetAddresses());
        for (InetAddress addr : addrs) {
            if (addr instanceof Inet6Address) {
                ipv6 = true;
                break;
            }
        }
    }
    if (!ipv6)
        System.out.println("IPv6 is not enabled on loopback. Skipping test suite.");
    return ipv6;
}
 
Example #14
Source File: ErrorSpecIPv6.java    From netphony-network-protocols with Apache License 2.0 6 votes vote down vote up
public ErrorSpecIPv6(){
	
	classNum = 6;
	cType = 2;
	length = 24;
	bytes = new byte[length];
	try{
		errorNodeAddress = (Inet6Address) Inet6Address.getLocalHost();
	}catch(UnknownHostException e){
		
	}
	flags = 0;
	errorCode = 0;
	errorValue = 0;
	
}
 
Example #15
Source File: LeaderElector.java    From dubbox with Apache License 2.0 6 votes vote down vote up
/**
 * 获取当前机子的IP地址拼接成字符串
 * 
 * @return 当前机子IP地址
 */
private String makeNodeTag() {
	StringBuilder sb = new StringBuilder();
	try {
		Enumeration<?> nis = NetworkInterface.getNetworkInterfaces();
		InetAddress ia = null;
		while (nis.hasMoreElements()) {
			NetworkInterface ni = (NetworkInterface) nis.nextElement();
			Enumeration<InetAddress> ias = ni.getInetAddresses();
			while (ias.hasMoreElements()) {
				ia = ias.nextElement();
				if (ia instanceof Inet6Address) {
					// skip ipv6
					continue;
				}
				sb.append(ia.getHostAddress() + ",");
			}
		}
		String ips = sb.toString();
		return ips.substring(0, ips.length() - 1);
	} catch (SocketException e) {
		log.error(e.getMessage(), e);
	}
	return null;
}
 
Example #16
Source File: IPUtils.java    From webmagic with Apache License 2.0 6 votes vote down vote up
public static String getFirstNoLoopbackIPAddresses() throws SocketException {

        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();

        InetAddress localAddress = null;
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = networkInterfaces.nextElement();
            Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
            while (inetAddresses.hasMoreElements()) {
                InetAddress address = inetAddresses.nextElement();
                if (!address.isLoopbackAddress() && !Inet6Address.class.isInstance(address)) {
                    return address.getHostAddress();
                } else if (!address.isLoopbackAddress()) {
                    localAddress = address;
                }
            }
        }

        return localAddress.getHostAddress();
    }
 
Example #17
Source File: Inet6AddressBlock.java    From armeria with Apache License 2.0 6 votes vote down vote up
Inet6AddressBlock(Inet6Address baseAddress, int maskBits) {
    this.baseAddress = requireNonNull(baseAddress, "baseAddress");
    checkArgument(maskBits >= 0 && maskBits <= 128,
                  "maskBits: %s (expected: 0-128)", maskBits);
    this.maskBits = maskBits;

    if (maskBits == 128) {
        lowerBound = upperBound = ipv6AddressToLongArray(baseAddress);
    } else if (maskBits == 0) {
        lowerBound = upperBound = new long[] { 0, 0 };
    } else {
        // Calculate the lower and upper bounds of this address block.
        // See Inet4AddressBlock if you want to know how they are calculated.
        final long[] mask = calculateMask(maskBits);
        lowerBound = calculateLowerBound(baseAddress, mask);
        upperBound = calculateUpperBound(lowerBound, mask);

        // If lowerBound is 0 and upperBound is 0xFFFFFFFFFFFFFFFF, skip comparing the value because
        // it covers all values.
        skipCompare[0] = lowerBound[0] == 0L && upperBound[0] == -1L;
        skipCompare[1] = lowerBound[1] == 0L && upperBound[1] == -1L;
    }
}
 
Example #18
Source File: OpenVPNService.java    From SimpleOpenVpn-Android with Apache License 2.0 6 votes vote down vote up
public void addRoutev6(String network, String device) {
    String[] v6parts = network.split("/");
    boolean included = isAndroidTunDevice(device);

    // Tun is opened after ROUTE6, no device name may be present

    try {
        Inet6Address ip = (Inet6Address) InetAddress.getAllByName(v6parts[0])[0];
        int mask = Integer.parseInt(v6parts[1]);
        mRoutesv6.addIPv6(ip, mask, included);

    } catch (UnknownHostException e) {
        VpnStatus.logException(e);
    }


}
 
Example #19
Source File: DHTPlugin.java    From BiglyBT with GNU General Public License v2.0 6 votes vote down vote up
@Override
public DHTPluginContact
importContact(
	InetSocketAddress				address )
{
	if ( !isEnabled()){

		throw( new RuntimeException( "DHT isn't enabled" ));
	}

	InetAddress contact_address = address.getAddress();

	for ( DHTPluginImpl dht: dhts ){

		InetAddress dht_address = dht.getLocalAddress().getAddress().getAddress();

		if ( 	( contact_address instanceof Inet4Address && dht_address instanceof Inet4Address ) ||
				( contact_address instanceof Inet6Address && dht_address instanceof Inet6Address )){

			return( dht.importContact( address ));
		}
	}

	return( null );
}
 
Example #20
Source File: InitialToken.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
private int getAddrType(InetAddress addr) {
    int addressType = CHANNEL_BINDING_AF_NULL_ADDR;

    if (addr instanceof Inet4Address)
        addressType = CHANNEL_BINDING_AF_INET;
    else if (addr instanceof Inet6Address)
        addressType = CHANNEL_BINDING_AF_INET6;
    return (addressType);
}
 
Example #21
Source File: IPv6TetheringCoordinator.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private static boolean isIPv6GlobalAddress(InetAddress ip) {
    return (ip instanceof Inet6Address) &&
           !ip.isAnyLocalAddress() &&
           !ip.isLoopbackAddress() &&
           !ip.isLinkLocalAddress() &&
           !ip.isSiteLocalAddress() &&
           !ip.isMulticastAddress();
}
 
Example #22
Source File: InetAddressUtil.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
public static String toAddrString(InetAddress ip) {
  checkNotNull(ip);
  if (ip instanceof Inet4Address) {
    // For IPv4, Java's formatting is good enough.
    return ip.getHostAddress();
  }
  checkArgument(ip instanceof Inet6Address);
  byte[] bytes = ip.getAddress();
  int[] hextets = new int[IPV6_PART_COUNT];
  for (int i = 0; i < hextets.length; i++) {
    hextets[i] = Ints.fromBytes((byte) 0, (byte) 0, bytes[2 * i], bytes[2 * i + 1]);
  }
  compressLongestRunOfZeroes(hextets);
  return hextetsToIPv6String(hextets);
}
 
Example #23
Source File: NetworkUtils.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Formats input address. For IPV4 returns simply host address, for IPV6 formats address according to <a
 * href="http://tools.ietf.org/html/rfc5952">RFC5952</a> rules. It embeds IPV6 address in '[', ']'.
 *
 * @param inet
 * @return
 */
public static String formatIPAddressForURI(InetAddress inet){
    if(inet == null){
        throw new IllegalArgumentException();
    }
    if(inet instanceof Inet4Address){
        return inet.getHostAddress();
    } else if (inet instanceof Inet6Address){
        return '[' + formatAddress(inet) + ']';
    } else {
        return inet.getHostAddress();
    }
}
 
Example #24
Source File: RpcStreamConnection.java    From p4ic4idea with Apache License 2.0 5 votes vote down vote up
private void getIpAddressFromSocketConnection() {
    if (nonNull(socket)) {
        InetAddress inetAddress = socket.getInetAddress();
        if (nonNull(inetAddress)) {
            // Check if it is an IPv6 address
            String hostAddress = inetAddress.getHostAddress();
            if (Inet6Address.class.isAssignableFrom(inetAddress.getClass())) {
                // Add the square brackets for IPv6 address
                hostIp = "[" + hostAddress + "]";
            } else {
                hostIp = hostAddress;
            }
        }
        if (socket.isBound()) {
            InetAddress address = socket.getLocalAddress();
            // Check if it is an IPv6 address
            if (Inet6Address.class.isAssignableFrom(address.getClass())) {
                // Add the square brackets for IPv6 address
                this.ourIp = "[" + address.getHostAddress() + "]";
            } else {
                this.ourIp = address.getHostAddress();
            }
            this.ourPort = socket.getLocalPort();
        }

    }
}
 
Example #25
Source File: Inet6AddressSerializationTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static String createOutputFileName(Inet6Address inet6Addr) {
    String inet6AddressOutputFilename;
    if (inet6Addr.getScopedInterface() != null) {
        inet6AddressOutputFilename = "IPV6Address_"
                + inet6Addr.getScopedInterface().getName() + ".out";
    } else {
        inet6AddressOutputFilename = "IPV6Address_"
                + Integer.valueOf(inet6Addr.getScopeId()).toString()
                + ".out";
    }
    return inet6AddressOutputFilename;
}
 
Example #26
Source File: NetUtils.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Encodes an IP address properly as a URL string. This method makes sure that IPv6 addresses
 * have the proper formatting to be included in URLs.
 *
 * @param address The IP address to encode.
 * @return The proper URL string encoded IP address.
 */
public static String ipAddressToUrlString(InetAddress address) {
	if (address == null) {
		throw new NullPointerException("address is null");
	}
	else if (address instanceof Inet4Address) {
		return address.getHostAddress();
	}
	else if (address instanceof Inet6Address) {
		return getIPv6UrlRepresentation((Inet6Address) address);
	}
	else {
		throw new IllegalArgumentException("Unrecognized type of InetAddress: " + address);
	}
}
 
Example #27
Source File: NetworkUtils.java    From elasticsearch-helper with Apache License 2.0 5 votes vote down vote up
public static InetAddress getFirstAddress(NetworkInterface networkInterface, ProtocolVersion ipVersion) throws SocketException {
    if (networkInterface == null) {
        throw new IllegalArgumentException("network interface is null");
    }
    for (Enumeration<InetAddress> addresses = networkInterface.getInetAddresses(); addresses.hasMoreElements(); ) {
        InetAddress address = addresses.nextElement();
        if ((address instanceof Inet4Address && ipVersion == ProtocolVersion.IPv4) ||
                (address instanceof Inet6Address && ipVersion == ProtocolVersion.IPv6)) {
            return address;
        }
    }
    return null;
}
 
Example #28
Source File: HostInfo.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
private DNSRecord.Pointer getDNS4ReverseAddressRecord(boolean unique, int ttl) {
    if (this.getInetAddress() instanceof Inet4Address) {
        return new DNSRecord.Pointer(this.getInetAddress().getHostAddress() + ".in-addr.arpa.", DNSRecordClass.CLASS_IN, unique, ttl, this.getName());
    }
    if ((this.getInetAddress() instanceof Inet6Address) && (((Inet6Address) this.getInetAddress()).isIPv4CompatibleAddress())) {
        byte[] rawAddress = this.getInetAddress().getAddress();
        String address = (rawAddress[12] & 0xff) + "." + (rawAddress[13] & 0xff) + "." + (rawAddress[14] & 0xff) + "." + (rawAddress[15] & 0xff);
        return new DNSRecord.Pointer(address + ".in-addr.arpa.", DNSRecordClass.CLASS_IN, unique, ttl, this.getName());
    }
    return null;
}
 
Example #29
Source File: BinlogHelper.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
static Address socketToProto(SocketAddress address) {
  checkNotNull(address, "address");

  Address.Builder builder = Address.newBuilder();
  if (address instanceof InetSocketAddress) {
    InetAddress inetAddress = ((InetSocketAddress) address).getAddress();
    if (inetAddress instanceof Inet4Address) {
      builder.setType(Type.TYPE_IPV4)
          .setAddress(InetAddressUtil.toAddrString(inetAddress));
    } else if (inetAddress instanceof Inet6Address) {
      builder.setType(Type.TYPE_IPV6)
          .setAddress(InetAddressUtil.toAddrString(inetAddress));
    } else {
      logger.log(Level.SEVERE, "unknown type of InetSocketAddress: {}", address);
      builder.setAddress(address.toString());
    }
    builder.setIpPort(((InetSocketAddress) address).getPort());
  } else if (address.getClass().getName().equals("io.netty.channel.unix.DomainSocketAddress")) {
    // To avoid a compile time dependency on grpc-netty, we check against the runtime class name.
    builder.setType(Type.TYPE_UNIX)
        .setAddress(address.toString());
  } else {
    builder.setType(Type.TYPE_UNKNOWN).setAddress(address.toString());
  }
  return builder.build();
}
 
Example #30
Source File: SelectorUtil.java    From TakinRPC with Apache License 2.0 5 votes vote down vote up
public static String normalizeHostAddress(final InetAddress localHost) {
    if (localHost instanceof Inet6Address) {
        return "[" + localHost.getHostAddress() + "]";
    } else {
        return localHost.getHostAddress();
    }
}