Java Code Examples for java.net.Inet6Address

The following examples show how to use java.net.Inet6Address. These examples are extracted from open source projects. 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 Project: BiglyBT   Source File: DHTPlugin.java    License: 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 2
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 3
Source Project: radar   Source File: IPUtil.java    License: 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 4
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 5
Source Project: jdk8u-jdk   Source File: JdpBroadcaster.java    License: 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 6
Source Project: PgBulkInsert   Source File: PgBulkInsertTest.java    License: 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 7
Source Project: netphony-network-protocols   Source File: SessionIPv6.java    License: 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 8
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 9
Source Project: webmagic   Source File: IPUtils.java    License: 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 10
Source Project: armeria   Source File: Inet6AddressBlock.java    License: 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 11
Source Project: dubbox   Source File: LeaderElector.java    License: 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 12
Source Project: netphony-network-protocols   Source File: ErrorSpecIPv6.java    License: 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 13
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 14
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 15
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 16
Source Project: EasyVPN-Free   Source File: OpenVPNService.java    License: 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 17
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 18
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 19
Source Project: SimpleOpenVpn-Android   Source File: OpenVPNService.java    License: 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 20
Source Project: grpc-nebula-java   Source File: InetAddressUtil.java    License: 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 21
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 22
Source Project: meshenger-android   Source File: Utils.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static List<InetSocketAddress> getAddressPermutations(String contact_mac, int port) {
    byte[] contact_mac_bytes = Utils.macAddressToBytes(contact_mac);
    ArrayList<InetSocketAddress> addrs = new ArrayList<InetSocketAddress>();
    try {
        List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface nif : all) {
            if (nif.isLoopback()) {
                continue;
            }

            for (InterfaceAddress ia : nif.getInterfaceAddresses()) {
                InetAddress addr = ia.getAddress();
                if (addr.isLoopbackAddress()) {
                    continue;
                }

                if (addr instanceof Inet6Address) {
                    Inet6Address addr6 = (Inet6Address) addr;
                    byte[] extracted_mac = getEUI64MAC(addr6);
                    if (extracted_mac != null && Arrays.equals(extracted_mac, nif.getHardwareAddress())) {
                        // We found the interface MAC address in the IPv6 assigned to that interface in the EUI-64 scheme.
                        // Now assume that the contact has an address with the same scheme.
                        InetAddress new_addr = createEUI64Address(addr6, contact_mac_bytes);
                        if (new_addr != null) {
                            addrs.add(new InetSocketAddress(new_addr, port));
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return addrs;
}
 
Example 23
Source Project: netty4.0.27Learn   Source File: NativeTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testAddressIpv6() throws Exception {
    Inet6Address address = NetUtil.LOCALHOST6;
    InetSocketAddress inetAddress = new InetSocketAddress(address, 9999);
    byte[] bytes = new byte[24];
    ByteBuffer buffer = ByteBuffer.wrap(bytes);
    buffer.put(address.getAddress());
    buffer.putInt(address.getScopeId());
    buffer.putInt(inetAddress.getPort());
    Assert.assertEquals(inetAddress, Native.address(buffer.array(), 0, bytes.length));
}
 
Example 24
Source Project: RipplePower   Source File: IP46Utils.java    License: Apache License 2.0 5 votes vote down vote up
public static int getType(Inet6Address a) {
	if (isUnspecified(a)) {
		return UNSPEC_TYPE;
	} else if (isLoopback(a)) {
		return LOOPBACK_TYPE;
	} else if (isMulticast(a)) {
		return MULTICAST_TYPE;
	} else if (isLLunicast(a)) {
		return LL_UNICAST_TYPE;
	} else if (isGLunicast(a)) {
		return GL_UNICAST_TYPE;
	}
	return -1;
}
 
Example 25
Source Project: lavaplayer   Source File: AbstractRoutePlanner.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public HttpRoute determineRoute(final HttpHost host, final HttpRequest request, final HttpContext context) throws HttpException {
  Args.notNull(request, "Request");
  if (host == null) {
    throw new ProtocolException("Target host is not specified");
  }
  final HttpClientContext clientContext = HttpClientContext.adapt(context);
  final RequestConfig config = clientContext.getRequestConfig();
  int remotePort;
  if (host.getPort() <= 0) {
    try {
      remotePort = schemePortResolver.resolve(host);
    } catch (final UnsupportedSchemeException e) {
      throw new HttpException(e.getMessage());
    }
  } else
    remotePort = host.getPort();

  final Tuple<Inet4Address, Inet6Address> remoteAddresses = IpAddressTools.getRandomAddressesFromHost(host);
  final Tuple<InetAddress, InetAddress> addresses = determineAddressPair(remoteAddresses);

  final HttpHost target = new HttpHost(addresses.r, host.getHostName(), remotePort, host.getSchemeName());
  final HttpHost proxy = config.getProxy();
  final boolean secure = target.getSchemeName().equalsIgnoreCase("https");
  clientContext.setAttribute(CHOSEN_IP_ATTRIBUTE, addresses.l);
  log.debug("Setting route context attribute to {}", addresses.l);
  if (proxy == null) {
    return new HttpRoute(target, addresses.l, secure);
  } else {
    return new HttpRoute(target, addresses.l, proxy, secure);
  }
}
 
Example 26
Source Project: j2objc   Source File: InetAddressTest.java    License: Apache License 2.0 5 votes vote down vote up
public void test_getByName_v6loopback() throws Exception {
    InetAddress inetAddress = InetAddress.getByName("::1");

    Set<InetAddress> expectedLoopbackAddresses =
            createSet(Inet4Address.LOOPBACK, Inet6Address.LOOPBACK);
    assertTrue(expectedLoopbackAddresses.contains(inetAddress));
}
 
Example 27
public static String normalizeHostAddress(final InetAddress localHost) {
    if (localHost instanceof Inet6Address) {
        return "[" + localHost.getHostAddress() + "]";
    } else {
        return localHost.getHostAddress();
    }
}
 
Example 28
static List<Inet6Address> getAllInet6Addresses() throws Exception {
    // System.err.println("\n getAllInet6Addresses: \n ");
    ArrayList<Inet6Address> inet6Addresses = new ArrayList<Inet6Address>();
    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(" address " + iadr);
                System.err.println(" scoped iface: "
                        + i6adr.getScopedInterface());
                // using this to actually set the hostName for an
                // InetAddress
                // created through the NetworkInterface
                // have found that the fabricated instances has a null
                // hostName
                System.err.println(" hostName: " + i6adr.getHostName());
                inet6Addresses.add(i6adr);
            }
        }
    }
    return inet6Addresses;
}
 
Example 29
Source Project: lavaplayer   Source File: RotatingNanoIpRoutePlanner.java    License: Apache License 2.0 5 votes vote down vote up
public RotatingNanoIpRoutePlanner(final List<IpBlock> ipBlocks, final Predicate<InetAddress> ipFilter, final boolean handleSearchFailure) {
  super(ipBlocks, handleSearchFailure);
  this.ipFilter = ipFilter;
  this.currentBlock = new AtomicReference<>(BigInteger.ZERO);
  this.blockNanoStart = new AtomicReference<>(BigInteger.valueOf(System.nanoTime()));
  this.next = new AtomicBoolean(false);
  if (ipBlock.getType() != Inet6Address.class || ipBlock.getSize().compareTo(Ipv6Block.BLOCK64_IPS) < 0)
    throw new IllegalArgumentException("Please use a bigger IPv6 Block!");
}
 
Example 30
Source Project: netty-4.1.22   Source File: NativeTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testAddressIpv6() throws Exception {
    Inet6Address address = NetUtil.LOCALHOST6;
    InetSocketAddress inetAddress = new InetSocketAddress(address, 9999);
    byte[] bytes = new byte[24];
    ByteBuffer buffer = ByteBuffer.wrap(bytes);
    buffer.put(address.getAddress());
    buffer.putInt(address.getScopeId());
    buffer.putInt(inetAddress.getPort());
    Assert.assertEquals(inetAddress, address(buffer.array(), 0, bytes.length));
}