Java Code Examples for java.net.Inet6Address

The following are top voted examples for showing how to use java.net.Inet6Address. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: jdk8u-jdk   File: Inet6AddressSerializationTest.java   Source Code and License 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
Project: CS4160-trustchain-android   File: BootstrapActivity.java   Source Code and License 6 votes vote down vote up
/**
     * When the user clicks the button to submit the ip address
     * this activity is finished and the ip is passed on as data to the previous activity.
     * @param view
     */
    public void onClickConnect(View view) {
        bootstrapView = (EditText) findViewById(R.id.bootstrap_IP);
        try{
            Object res = InetAddress.getByName(bootstrapView.getText().toString());
            if(!(res instanceof Inet4Address) && !(res instanceof Inet6Address)){
                Log.i("Bootstrap IP Adress: ", res.toString());
                throw new Exception("Bootstrap IP is not a valid IP4 or IP6 address.");
            }
            Intent returnIntent = new Intent();
            BootstrapIPStorage.setIP(this, bootstrapView.getText().toString());
            returnIntent.putExtra("ConnectableAddress",bootstrapView.getText().toString());
            setResult(OverviewConnectionsActivity.RESULT_OK,returnIntent);
            finish();
        } catch (Exception e){
            Toast.makeText(this, "The bootstrap IP address is not a valid IP address: " + bootstrapView.getText().toString(), Toast.LENGTH_SHORT).show();
//             e.printStackTrace();
        }
    }
 
Example 3
Project: openjdk-jdk10   File: Inet6AddressSerializationTest.java   Source Code and License 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 4
Project: fuck_zookeeper   File: ConnectionBean.java   Source Code and License 6 votes vote down vote up
public ConnectionBean(ServerCnxn connection,ZooKeeperServer zk){
    this.connection = connection;
    this.stats = connection;
    this.zk = zk;
    
    InetSocketAddress sockAddr = connection.getRemoteSocketAddress();
    if (sockAddr == null) {
        remoteIP = "Unknown";
    } else {
        InetAddress addr = sockAddr.getAddress();
        if (addr instanceof Inet6Address) {
            remoteIP = ObjectName.quote(addr.getHostAddress());
        } else {
            remoteIP = addr.getHostAddress();
        }
    }
    sessionId = connection.getSessionId();
}
 
Example 5
Project: guava-mock   File: InetAddresses.java   Source Code and License 6 votes vote down vote up
/**
 * Returns the string representation of an {@link InetAddress}.
 *
 * <p>For IPv4 addresses, this is identical to {@link InetAddress#getHostAddress()}, but for IPv6
 * addresses, the output follows <a href="http://tools.ietf.org/html/rfc5952">RFC 5952</a> section
 * 4. The main difference is that this method uses "::" for zero compression, while Java's version
 * uses the uncompressed form.
 *
 * <p>This method uses hexadecimal for all IPv6 addresses, including IPv4-mapped IPv6 addresses
 * such as "::c000:201". The output does not include a Scope ID.
 *
 * @param ip {@link InetAddress} to be converted to an address string
 * @return {@code String} containing the text-formatted IP address
 * @since 10.0
 */
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 6
Project: guava-mock   File: InetAddresses.java   Source Code and License 6 votes vote down vote up
/**
 * Returns the Teredo information embedded in a Teredo address.
 *
 * @param ip {@link Inet6Address} to be examined for embedded Teredo information
 * @return extracted {@code TeredoInfo}
 * @throws IllegalArgumentException if the argument is not a valid IPv6 Teredo address
 */
public static TeredoInfo getTeredoInfo(Inet6Address ip) {
  checkArgument(isTeredoAddress(ip), "Address '%s' is not a Teredo address.", toAddrString(ip));

  byte[] bytes = ip.getAddress();
  Inet4Address server = getInet4Address(Arrays.copyOfRange(bytes, 4, 8));

  int flags = ByteStreams.newDataInput(bytes, 8).readShort() & 0xffff;

  // Teredo obfuscates the mapped client port, per section 4 of the RFC.
  int port = ~ByteStreams.newDataInput(bytes, 10).readShort() & 0xffff;

  byte[] clientBytes = Arrays.copyOfRange(bytes, 12, 16);
  for (int i = 0; i < clientBytes.length; i++) {
    // Teredo obfuscates the mapped client IP, per section 4 of the RFC.
    clientBytes[i] = (byte) ~clientBytes[i];
  }
  Inet4Address client = getInet4Address(clientBytes);

  return new TeredoInfo(server, client, port, flags);
}
 
Example 7
Project: guava-mock   File: InetAddresses.java   Source Code and License 6 votes vote down vote up
/**
 * Evaluates whether the argument is an ISATAP address.
 *
 * <p>From RFC 5214: "ISATAP interface identifiers are constructed in Modified EUI-64 format [...]
 * by concatenating the 24-bit IANA OUI (00-00-5E), the 8-bit hexadecimal value 0xFE, and a 32-bit
 * IPv4 address in network byte order [...]"
 *
 * <p>For more on ISATAP addresses see section 6.1 of
 * <a target="_parent" href="http://tools.ietf.org/html/rfc5214#section-6.1">RFC 5214</a>.
 *
 * @param ip {@link Inet6Address} to be examined for ISATAP address format
 * @return {@code true} if the argument is an ISATAP address
 */
public static boolean isIsatapAddress(Inet6Address ip) {

  // If it's a Teredo address with the right port (41217, or 0xa101)
  // which would be encoded as 0x5efe then it can't be an ISATAP address.
  if (isTeredoAddress(ip)) {
    return false;
  }

  byte[] bytes = ip.getAddress();

  if ((bytes[8] | (byte) 0x03) != (byte) 0x03) {

    // Verify that high byte of the 64 bit identifier is zero, modulo
    // the U/L and G bits, with which we are not concerned.
    return false;
  }

  return (bytes[9] == (byte) 0x00) && (bytes[10] == (byte) 0x5e) && (bytes[11] == (byte) 0xfe);
}
 
Example 8
Project: googles-monorepo-demo   File: InetAddresses.java   Source Code and License 6 votes vote down vote up
/**
 * Returns the Teredo information embedded in a Teredo address.
 *
 * @param ip {@link Inet6Address} to be examined for embedded Teredo information
 * @return extracted {@code TeredoInfo}
 * @throws IllegalArgumentException if the argument is not a valid IPv6 Teredo address
 */
public static TeredoInfo getTeredoInfo(Inet6Address ip) {
  checkArgument(isTeredoAddress(ip), "Address '%s' is not a Teredo address.", toAddrString(ip));

  byte[] bytes = ip.getAddress();
  Inet4Address server = getInet4Address(Arrays.copyOfRange(bytes, 4, 8));

  int flags = ByteStreams.newDataInput(bytes, 8).readShort() & 0xffff;

  // Teredo obfuscates the mapped client port, per section 4 of the RFC.
  int port = ~ByteStreams.newDataInput(bytes, 10).readShort() & 0xffff;

  byte[] clientBytes = Arrays.copyOfRange(bytes, 12, 16);
  for (int i = 0; i < clientBytes.length; i++) {
    // Teredo obfuscates the mapped client IP, per section 4 of the RFC.
    clientBytes[i] = (byte) ~clientBytes[i];
  }
  Inet4Address client = getInet4Address(clientBytes);

  return new TeredoInfo(server, client, port, flags);
}
 
Example 9
Project: openjdk-jdk10   File: JMXServiceURL.java   Source Code and License 6 votes vote down vote up
private String getActiveNetworkInterfaceIP() throws SocketException {
    Enumeration<NetworkInterface>
            networkInterface = NetworkInterface.getNetworkInterfaces();
    String ipv6AddrStr = null;
    while (networkInterface.hasMoreElements()) {
        NetworkInterface nic = networkInterface.nextElement();
        if (nic.isUp() && !nic.isLoopback()) {
            Enumeration<InetAddress> inet = nic.getInetAddresses();
            while (inet.hasMoreElements()) {
                InetAddress addr = inet.nextElement();
                if (addr instanceof Inet4Address
                        && !addr.isLinkLocalAddress()) {
                    return addr.getHostAddress();
                }else if (addr instanceof Inet6Address
                        && !addr.isLinkLocalAddress()) {
                    /*
                    We save last seen IPv6 address which we will return
                    if we do not find any interface with IPv4 address.
                    */
                    ipv6AddrStr = addr.getHostAddress();
                }
            }
        }
    }
    return ipv6AddrStr;
}
 
Example 10
Project: hekate   File: AddressPattern.java   Source Code and License 6 votes vote down vote up
private boolean ipVersionMatch(InetAddress addr) {
    if (opts.ipVersion() != null) {
        switch (opts.ipVersion()) {
            case V4: {
                return addr instanceof Inet4Address;
            }
            case V6: {
                return addr instanceof Inet6Address;
            }
            default: {
                throw new IllegalStateException("Unexpected IP version type: " + opts.ipVersion());
            }
        }
    }

    return true;
}
 
Example 11
Project: hekate   File: MulticastSeedNodeProvider.java   Source Code and License 6 votes vote down vote up
/**
 * Constructs new instance.
 *
 * @param cfg Configuration.
 *
 * @throws UnknownHostException If failed to resolve multicast group address.
 */
public MulticastSeedNodeProvider(MulticastSeedNodeProviderConfig cfg) throws UnknownHostException {
    ConfigCheck check = ConfigCheck.get(getClass());

    check.notNull(cfg, "configuration");
    check.positive(cfg.getPort(), "port");
    check.nonNegative(cfg.getTtl(), "TTL");
    check.notEmpty(cfg.getGroup(), "multicast group");
    check.positive(cfg.getInterval(), "discovery interval");
    check.positive(cfg.getWaitTime(), "wait time");
    check.that(cfg.getInterval() < cfg.getWaitTime(), "discovery interval must be greater than wait time "
        + "[discovery-interval=" + cfg.getInterval() + ", wait-time=" + cfg.getWaitTime() + ']');

    InetAddress groupAddress = InetAddress.getByName(cfg.getGroup());

    check.isTrue(groupAddress.isMulticastAddress(), "address is not a multicast address [address=" + groupAddress + ']');

    group = new InetSocketAddress(groupAddress, cfg.getPort());
    ttl = cfg.getTtl();
    interval = cfg.getInterval();
    waitTime = cfg.getWaitTime();
    loopBackDisabled = cfg.isLoopBackDisabled();

    ipVer = group.getAddress() instanceof Inet6Address ? InternetProtocolFamily.IPv6 : InternetProtocolFamily.IPv4;
}
 
Example 12
Project: jdk8u-jdk   File: Inet6AddressSerializationTest.java   Source Code and License 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 13
Project: openjdk-jdk10   File: NetworkConfigurationProbe.java   Source Code and License 6 votes vote down vote up
public static void main(String... args) throws Exception {
    NetworkConfiguration.printSystemConfiguration(out);

    NetworkConfiguration nc = NetworkConfiguration.probe();
    String list;
    list = nc.ip4MulticastInterfaces()
              .map(NetworkInterface::getName)
              .collect(joining(" "));
    out.println("ip4MulticastInterfaces: " +  list);

    list = nc.ip4Addresses()
              .map(Inet4Address::toString)
              .collect(joining(" "));
    out.println("ip4Addresses: " +  list);

    list = nc.ip6MulticastInterfaces()
              .map(NetworkInterface::getName)
              .collect(joining(" "));
    out.println("ip6MulticastInterfaces: " +  list);

    list = nc.ip6Addresses()
              .map(Inet6Address::toString)
              .collect(joining(" "));
    out.println("ip6Addresses: " +  list);
}
 
Example 14
Project: Daedalus   File: DaedalusVpnService.java   Source Code and License 6 votes vote down vote up
private InetAddress addDnsServer(Builder builder, String format, byte[] ipv6Template, InetAddress address) throws UnknownHostException {
    int size = dnsServers.size();
    size++;
    if (address instanceof Inet6Address && ipv6Template == null) {
        Log.i(TAG, "addDnsServer: Ignoring DNS server " + address);
    } else if (address instanceof Inet4Address) {
        String alias = String.format(format, size + 1);
        dnsServers.put(alias, address.getHostAddress());
        builder.addRoute(alias, 32);
        return InetAddress.getByName(alias);
    } else if (address instanceof Inet6Address) {
        ipv6Template[ipv6Template.length - 1] = (byte) (size + 1);
        InetAddress i6addr = Inet6Address.getByAddress(ipv6Template);
        dnsServers.put(i6addr.getHostAddress(), address.getHostAddress());
        return i6addr;
    }
    return null;
}
 
Example 15
Project: monarch   File: JGAddress.java   Source Code and License 6 votes vote down vote up
@Override
public void writeTo(DataOutput out) throws Exception {
  if (ip_addr != null) {
    byte[] address = ip_addr.getAddress(); // 4 bytes (IPv4) or 16 bytes (IPv6)
    out.writeByte(address.length); // 1 byte
    out.write(address, 0, address.length);
    if (ip_addr instanceof Inet6Address)
      out.writeInt(((Inet6Address) ip_addr).getScopeId());
  } else {
    out.writeByte(0);
  }
  out.writeShort(port);
  out.writeInt(vmViewId);
  out.writeLong(mostSigBits);
  out.writeLong(leastSigBits);
}
 
Example 16
Project: RISE-V2G   File: UDPServer.java   Source Code and License 6 votes vote down vote up
public boolean send(V2GTPMessage message, Inet6Address udpClientAddress, int udpClientPort) {
	 byte[] v2gTPMessage = message.getMessage();
	// Set up the UDP packet containing the V2GTP message to be sent to the UDP client
	DatagramPacket udpServerPacket = new DatagramPacket(v2gTPMessage, 
														v2gTPMessage.length,
														udpClientAddress,
														udpClientPort);
	
	// Send the response to the UDP client
	try {
		udpServerSocket.send(udpServerPacket);
		getLogger().debug("Message sent");
		
		return true;
	} catch (IOException e) {
		getLogger().error("UDP response failed (IOException) while trying to send message!", e);
		return false;
	}
}
 
Example 17
Project: EasyDiameter   File: AddressAVP.java   Source Code and License 6 votes vote down vote up
public void setData(InetAddress data) {
	if (data instanceof Inet4Address) {
		this.addressType = ADDRESS_TYPE_IPv4;
		this.address = data;
		byteData = new byte[6];
		byteData[1] = ADDRESS_TYPE_IPv4;
		System.arraycopy(data.getAddress(), 0, byteData, 2, 4);
		addDataLength(6);
	} else if (data instanceof Inet6Address) {
		this.addressType = ADDRESS_TYPE_IPv6;
		this.address = data;
		byteData = new byte[18];
		byteData[1] = ADDRESS_TYPE_IPv6;
		System.arraycopy(data.getAddress(), 0, byteData, 2, 16);
		addDataLength(18);
	} else {
		// TODO: Throw Custom Error
	}
}
 
Example 18
Project: datatree-adapters   File: JsonIon.java   Source Code and License 6 votes vote down vote up
public void addDefaultSerializers() {

		// InetAddress
		addSerializer(converters, InetAddress.class, (value) -> {
			return value.getCanonicalHostName();
		});
		addSerializer(converters, Inet4Address.class, (value) -> {
			return value.getCanonicalHostName();
		});
		addSerializer(converters, Inet6Address.class, (value) -> {
			return value.getCanonicalHostName();
		});

		// UUID
		addSerializer(converters, UUID.class, (value) -> {
			return value.toString();
		});
	}
 
Example 19
Project: datatree-adapters   File: JsonGenson.java   Source Code and License 6 votes vote down vote up
public static final Genson create(boolean pretty) {
	GensonBuilder builder = new GensonBuilder();

	// Install MongoDB / BSON serializers
	tryToAddSerializers("io.datatree.dom.adapters.JsonGensonBsonSerializers", builder);

	// Install serializers for Apache Cassandra
	addSerializer(builder, InetAddress.class, (value, writer, ctx) -> {
		writer.writeString(value.getCanonicalHostName());
	});
	addSerializer(builder, Inet4Address.class, (value, writer, ctx) -> {
		writer.writeString(value.getCanonicalHostName());
	});
	addSerializer(builder, Inet6Address.class, (value, writer, ctx) -> {
		writer.writeString(value.getCanonicalHostName());
	});

	// Set Date format
	builder.useDateAsTimestamp(!Config.USE_TIMESTAMPS);
	if (Config.USE_TIMESTAMPS) {
		builder.useDateFormat(new SimpleDateFormat(Config.TIMESTAMP_FORMAT));
	}
	builder.useIndentation(pretty);
	return builder.create();
}
 
Example 20
Project: athena   File: IpAddress.java   Source Code and License 6 votes vote down vote up
/**
 * Converts an InetAddress into an IP address.
 *
 * @param inetAddress the InetAddress value to use
 * @return an IP address
 * @throws IllegalArgumentException if the argument is invalid
 */
public static IpAddress valueOf(InetAddress inetAddress) {
    byte[] bytes = inetAddress.getAddress();
    if (inetAddress instanceof Inet4Address) {
        return new IpAddress(Version.INET, bytes);
    }
    if (inetAddress instanceof Inet6Address) {
        return new IpAddress(Version.INET6, bytes);
    }
    // Use the number of bytes as a hint
    if (bytes.length == INET_BYTE_LENGTH) {
        return new IpAddress(Version.INET, bytes);
    }
    if (bytes.length == INET6_BYTE_LENGTH) {
        return new IpAddress(Version.INET6, bytes);
    }
    final String msg = "Unrecognized IP version address string: " +
        inetAddress.toString();
    throw new IllegalArgumentException(msg);
}
 
Example 21
Project: BiglyBT   File: DHTPlugin.java   Source Code and License 6 votes vote down vote up
@Override
public DHTPluginContact
importContact(
	InetSocketAddress				address,
	byte							version )
{
	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, version ));
		}
	}

	return( null );
}
 
Example 22
Project: openjdk-jdk10   File: Inet6AddressSerializationTest.java   Source Code and License 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 23
Project: openjdk-jdk10   File: JdpBroadcaster.java   Source Code and License 5 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);

        if (interf == null) {
            throw new JdpException("Unable to get network interface for " + srcAddress.toString());
        }

        if (!interf.isUp()) {
            throw new JdpException(interf.getName() + " is not up.");
        }

        if (!interf.supportsMulticast()) {
            throw new JdpException(interf.getName() + " does not support multicast.");
        }

        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 24
Project: jdk8u-jdk   File: Inet6AddressSerializationTest.java   Source Code and License 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 25
Project: cyberduck   File: ProxySocketFactoryTest.java   Source Code and License 5 votes vote down vote up
@Test
@Ignore
public void testConnectIPv6LocalAddress() throws Exception {
    for(String address : Arrays.asList("fe80::c62c:3ff:fe0b:8670")) {
        final Socket socket = new ProxySocketFactory(new TestProtocol(), new TrustManagerHostnameCallback() {
            @Override
            public String getTarget() {
                return "localhost";
            }
        }).withBlacklistedNetworkInterfaces(Arrays.asList("awdl0")).createSocket(address, 22);
        assertNotNull(socket);
        assertTrue(socket.getInetAddress() instanceof Inet6Address);
    }
}
 
Example 26
Project: AgentWorkbench   File: JadeUrlConfiguration.java   Source Code and License 5 votes vote down vote up
/**
 * Sets the local InetAddress's.
 */
private void setLocalInetAddresses() {
	
	try {
		Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
		for (NetworkInterface netint : Collections.list(nets)) {

			Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
			if (inetAddresses.hasMoreElements()) {
				// System.out.printf("Display name: %s\n",
				// netint.getDisplayName());
				// System.out.printf("Name: %s\n", netint.getName());
				for (InetAddress inetAddress : Collections.list(inetAddresses)) {
					if (inetAddress instanceof Inet4Address) {
						if (this.getLocalIP4InetAddresses().contains(inetAddress)==false) {
							this.getLocalIP4InetAddresses().add(inetAddress);	
						}
						
					} else if (inetAddress instanceof Inet6Address) {
						if (this.getLocalIP6InetAddresses().contains(inetAddress)==false) {
							this.getLocalIP6InetAddresses().add(inetAddress);	
						}
						
					}
				}
			}
		}

	} catch (SocketException e) {
		System.err.println("Error retrieving local network addresses list ... ");
	}
}
 
Example 27
Project: ZooKeeper   File: ZKTestCase.java   Source Code and License 5 votes vote down vote up
protected void assumeIPv6Available() {
    try {
        InetAddress address = Inet6Address.getByName("0:0:0:0:0:0:0:1");
        Assume.assumeTrue(address.isReachable(1000));
    } catch (IOException exception) {
        Assume.assumeTrue(false);
    }
}
 
Example 28
Project: AgentWorkbench   File: NetworkAddresses.java   Source Code and License 5 votes vote down vote up
@Override
public String toString() {
	
	String description = null; 
	switch (this.getInetAddressType()) {
	case Inet4Address:
		description = "[IP4] " + this.inetAddress.getHostAddress() + " (" + this.networkInterface.getName() + " - " + this.networkInterface.getDisplayName() + ")";
		break;

	case Inet6Address:
		description = "[IP6] " + this.inetAddress.getHostAddress() + " (" + this.networkInterface.getName() + " - " + this.networkInterface.getDisplayName() + ")";
		break;
	}
	return description;
}
 
Example 29
Project: stynico   File: RegisterActivity.java   Source Code and License 5 votes vote down vote up
public static String getHostIP() {

        String hostIp = null;
        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) {
                        continue;// skip ipv6
                    }
                    String ip = ia.getHostAddress();
                    if (!"127.0.0.1".equals(ip)) {
                        hostIp = ia.getHostAddress();
                        break;
                    }
                }
            }
        } catch (SocketException e) {
            // Log.i("yao", "SocketException");
            e.printStackTrace();
        }
        return hostIp;

    }
 
Example 30
Project: url-classifier   File: AuthorityClassifierBuilderTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testOneIpv6() {
  runCommonTestsWith(
      AuthorityClassifiers.builder()
      .host(InetAddresses.forUriString("[3ffe:0:0:0:0:0:0:1]"))
      .build(),
      "http://[3ffe:0:0:0:0:0:0:1]/"
      );
  runCommonTestsWith(
      AuthorityClassifiers.builder()
      .host((Inet6Address) InetAddresses.forUriString("[3ffe:0:0:0:0:0:0:1]"))
      .build(),
      "http://[3ffe:0:0:0:0:0:0:1]/"
      );
}
 
Example 31
Project: mac-address-detector-java   File: MacAddressHelper.java   Source Code and License 5 votes vote down vote up
/**
 * The broadcast mac address for a icmpv6 request is replaced all bytes with 33:33:ff except the last thress bytes
 * fe80::250:56ff:fe95:f8d -> 33:33:ff:95:0f:8d
 *
 * @param inet6Address
 * @return
 */
private MacAddress _getBroadcastMacAddress4IPv6(Inet6Address inet6Address) {
    byte[] ipInBytes = inet6Address.getAddress();
    byte[] broadcastMacAddress = new byte[_IPv6_BROADCAST_MACADDRESS_PREFIX.length];
    System.arraycopy(_IPv6_BROADCAST_MACADDRESS_PREFIX, 0, broadcastMacAddress, 0, _IPv6_BROADCAST_MACADDRESS_PREFIX.length);
    int reservedBytes = 3;
    System.arraycopy(ipInBytes, ipInBytes.length - reservedBytes, broadcastMacAddress, _IPv6_BROADCAST_MACADDRESS_PREFIX.length -
            reservedBytes, reservedBytes);
    return MacAddress.getByAddress(broadcastMacAddress);
}
 
Example 32
Project: wechat-mall   File: RemotingUtil.java   Source Code and License 5 votes vote down vote up
public static String normalizeHostAddress(final InetAddress localHost) {
    if (localHost instanceof Inet6Address) {
        return "[" + localHost.getHostAddress() + "]";
    }
    else {
        return localHost.getHostAddress();
    }
}
 
Example 33
Project: xdman   File: FTP.java   Source Code and License 5 votes vote down vote up
/***
 * A convenience method to send the FTP EPRT command to the server,
 * receive the reply, and return the reply code.
 *
 * Examples:
 * <code>
 * <ul>
 * <li>EPRT |1|132.235.1.2|6275|</li>
 * <li>EPRT |2|1080::8:800:200C:417A|5282|</li>
 * </ul>
 * </code>
 * <p>
 * @see "http://www.faqs.org/rfcs/rfc2428.html"
 *
 * @param host  The host owning the port.
 * @param port  The new port.
 * @return The reply code received from the server.
 * @exception FTPConnectionClosedException
 *      If the FTP server prematurely closes the connection as a result
 *      of the client being idle or some other reason causing the server
 *      to send FTP reply code 421.  This exception may be caught either
 *      as an IOException or independently as itself.
 * @exception IOException  If an I/O error occurs while either sending the
 *      command or receiving the server reply.
 * @since 2.2
 ***/
public int eprt(InetAddress host, int port) throws IOException
{
    int num;
    StringBuilder info = new StringBuilder();
    String h;

    // If IPv6, trim the zone index
    h = host.getHostAddress();
    num = h.indexOf("%");
    if (num > 0) {
        h = h.substring(0, num);
    }

    info.append("|");

    if (host instanceof Inet4Address) {
        info.append("1");
    } else if (host instanceof Inet6Address) {
        info.append("2");
    }
    info.append("|");
    info.append(h);
    info.append("|");
    info.append(port);
    info.append("|");

    return sendCommand(FTPCommand.EPRT, info.toString());
}
 
Example 34
Project: elasticsearch_my   File: IfConfig.java   Source Code and License 5 votes vote down vote up
/** format internet address: java's default doesn't include everything useful */
private static String formatAddress(InterfaceAddress interfaceAddress) throws IOException {
    StringBuilder sb = new StringBuilder();

    InetAddress address = interfaceAddress.getAddress();
    if (address instanceof Inet6Address) {
        sb.append("inet6 ");
        sb.append(NetworkAddress.format(address));
        sb.append(" prefixlen:");
        sb.append(interfaceAddress.getNetworkPrefixLength());
    } else {
        sb.append("inet ");
        sb.append(NetworkAddress.format(address));
        int netmask = 0xFFFFFFFF << (32 - interfaceAddress.getNetworkPrefixLength());
        sb.append(" netmask:" + NetworkAddress.format(InetAddress.getByAddress(new byte[] {
                (byte)(netmask >>> 24),
                (byte)(netmask >>> 16 & 0xFF),
                (byte)(netmask >>> 8 & 0xFF),
                (byte)(netmask & 0xFF)
        })));
        InetAddress broadcast = interfaceAddress.getBroadcast();
        if (broadcast != null) {
            sb.append(" broadcast:" + NetworkAddress.format(broadcast));
        }
    }
    if (address.isLoopbackAddress()) {
        sb.append(" scope:host");
    } else if (address.isLinkLocalAddress()) {
        sb.append(" scope:link");
    } else if (address.isSiteLocalAddress()) {
        sb.append(" scope:site");
    }
    return sb.toString();
}
 
Example 35
Project: elasticsearch_my   File: NetworkUtils.java   Source Code and License 5 votes vote down vote up
/** Returns only the IPV6 addresses in {@code addresses} */
static InetAddress[] filterIPV6(InetAddress addresses[]) {
    List<InetAddress> list = new ArrayList<>();
    for (InetAddress address : addresses) {
        if (address instanceof Inet6Address) {
            list.add(address);
        }
    }
    if (list.isEmpty()) {
        throw new IllegalArgumentException("No ipv6 addresses found in " + Arrays.toString(addresses));
    }
    return list.toArray(new InetAddress[list.size()]);
}
 
Example 36
Project: ditb   File: Addressing.java   Source Code and License 5 votes vote down vote up
public static InetAddress getIpAddress() throws SocketException {
  return getIpAddress(new AddressSelectionCondition() {
    @Override
    public boolean isAcceptableAddress(InetAddress addr) {
      return addr instanceof Inet4Address || addr instanceof Inet6Address;
    }
  });
}
 
Example 37
Project: OpenJSharp   File: HostAddresses.java   Source Code and License 5 votes vote down vote up
/**
 * Returns all the IP addresses of the local host.
 */
public static HostAddresses getLocalAddresses() throws IOException
{
    String hostname = null;
    InetAddress[] inetAddresses = null;
    try {
        InetAddress localHost = InetAddress.getLocalHost();
        hostname = localHost.getHostName();
        inetAddresses = InetAddress.getAllByName(hostname);
        HostAddress[] hAddresses = new HostAddress[inetAddresses.length];
        for (int i = 0; i < inetAddresses.length; i++)
            {
                hAddresses[i] = new HostAddress(inetAddresses[i]);
            }
        if (DEBUG) {
            System.out.println(">>> KrbKdcReq local addresses for "
                               + hostname + " are: ");

            for (int i = 0; i < inetAddresses.length; i++) {
                System.out.println("\n\t" + inetAddresses[i]);
                if (inetAddresses[i] instanceof Inet4Address)
                    System.out.println("IPv4 address");
                if (inetAddresses[i] instanceof Inet6Address)
                    System.out.println("IPv6 address");
            }
        }
        return (new HostAddresses(hAddresses));
    } catch (Exception exc) {
        throw new IOException(exc.toString());
    }

}
 
Example 38
Project: jdk8u-jdk   File: HostAddresses.java   Source Code and License 5 votes vote down vote up
/**
 * Returns all the IP addresses of the local host.
 */
public static HostAddresses getLocalAddresses() throws IOException
{
    String hostname = null;
    InetAddress[] inetAddresses = null;
    try {
        InetAddress localHost = InetAddress.getLocalHost();
        hostname = localHost.getHostName();
        inetAddresses = InetAddress.getAllByName(hostname);
        HostAddress[] hAddresses = new HostAddress[inetAddresses.length];
        for (int i = 0; i < inetAddresses.length; i++)
            {
                hAddresses[i] = new HostAddress(inetAddresses[i]);
            }
        if (DEBUG) {
            System.out.println(">>> KrbKdcReq local addresses for "
                               + hostname + " are: ");

            for (int i = 0; i < inetAddresses.length; i++) {
                System.out.println("\n\t" + inetAddresses[i]);
                if (inetAddresses[i] instanceof Inet4Address)
                    System.out.println("IPv4 address");
                if (inetAddresses[i] instanceof Inet6Address)
                    System.out.println("IPv6 address");
            }
        }
        return (new HostAddresses(hAddresses));
    } catch (Exception exc) {
        throw new IOException(exc.toString());
    }

}
 
Example 39
Project: Nird2   File: PrivacyUtils.java   Source Code and License 5 votes vote down vote up
@Nullable
public static String scrubInetAddress(InetAddress address) {
	// don't scrub link and site local addresses
	if (address.isLinkLocalAddress() || address.isSiteLocalAddress())
		return address.toString();
	// completely scrub IPv6 addresses
	if (address instanceof Inet6Address) return "[scrubbed]";
	// keep first and last octet of IPv4 addresses
	return scrubInetAddress(address.toString());
}
 
Example 40
Project: Nird2   File: PrivacyUtils.java   Source Code and License 5 votes vote down vote up
@Nullable
public static String scrubInetAddress(InetAddress address) {
	// don't scrub link and site local addresses
	if (address.isLinkLocalAddress() || address.isSiteLocalAddress())
		return address.toString();
	// completely scrub IPv6 addresses
	if (address instanceof Inet6Address) return "[scrubbed]";
	// keep first and last octet of IPv4 addresses
	return scrubInetAddress(address.toString());
}
 
Example 41
Project: fuck_zookeeper   File: ZKTestCase.java   Source Code and License 5 votes vote down vote up
protected void assumeIPv6Available() {
    try {
        InetAddress address = Inet6Address.getByName("0:0:0:0:0:0:0:1");
        Assume.assumeTrue(address.isReachable(1000));
    } catch (IOException exception) {
        Assume.assumeTrue(false);
    }
}
 
Example 42
Project: BiglyBT   File: DHTPlugin.java   Source Code and License 5 votes vote down vote up
@Override
public DHTPluginContact
importContact(
	InetSocketAddress				address,
	byte							version,
	boolean							is_cvs )
{
	if ( !isEnabled()){

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

	InetAddress contact_address = address.getAddress();

	int	target_network = is_cvs?DHT.NW_AZ_CVS:DHT.NW_AZ_MAIN;

	for ( DHTPluginImpl dht: dhts ){

		if ( dht.getDHT().getTransport().getNetwork() != target_network ){

			continue;
		}

		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, version ));
		}
	}

		// fallback

	return( importContact( address, version ));
}
 
Example 43
Project: abhot   File: Util.java   Source Code and License 5 votes vote down vote up
private static boolean isGoodV6Address(InetAddress address)
{
	return address instanceof Inet6Address &&
			!address.isAnyLocalAddress() &&
			!address.isLoopbackAddress() &&
			!address.isMulticastAddress();
}
 
Example 44
Project: hekate   File: AddressPatternTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testIpVersion() throws Exception {
    AddressPattern selectorIp4 = createSelector("ip4~.*");

    assertTrue(selectorIp4.select() instanceof Inet4Address);

    if (ipV6Supported) {
        AddressPattern selectorIp6 = createSelector("ip6~.*");

        assertSame(AddressPatternOpts.IpVersion.V6, selectorIp6.opts().ipVersion());

        assertTrue(selectorIp6.select() instanceof Inet6Address);
    }
}
 
Example 45
Project: open-rmbt   File: Helperfunctions.java   Source Code and License 5 votes vote down vote up
public static String IpType(InetAddress inetAddress)
{
    try
    {
        final String ipVersion;
        if (inetAddress instanceof Inet4Address)
            ipVersion = "ipv4";
        else if (inetAddress instanceof Inet6Address)
            ipVersion = "ipv6";
        else
            ipVersion = "ipv?";
        
        if (inetAddress.isAnyLocalAddress())
            return "wildcard_" + ipVersion;
        if (inetAddress.isSiteLocalAddress())
            return "site_local_" + ipVersion;
        if (inetAddress.isLinkLocalAddress())
            return "link_local_" + ipVersion;
        if (inetAddress.isLoopbackAddress())
            return "loopback_" + ipVersion;
        return "public_" + ipVersion;

    }
    catch (final IllegalArgumentException e)
    {
        return "illegal_ip";
    }
}
 
Example 46
Project: open-rmbt   File: Helperfunctions.java   Source Code and License 5 votes vote down vote up
public static Long getASN(final InetAddress adr)
{
    try
    {
        final Name postfix;
        if (adr instanceof Inet6Address)
            postfix = Name.fromConstantString("origin6.asn.cymru.com");
        else
            postfix = Name.fromConstantString("origin.asn.cymru.com");
        
        final Name name = getReverseIPName(adr, postfix);
        System.out.println("lookup: " + name);
        
        final Lookup lookup = new Lookup(name, Type.TXT);
        lookup.setResolver(new SimpleResolver());
        lookup.setCache(null);
        final Record[] records = lookup.run();
        if (lookup.getResult() == Lookup.SUCCESSFUL)
            for (final Record record : records)
                if (record instanceof TXTRecord)
                {
                    final TXTRecord txt = (TXTRecord) record;
                    @SuppressWarnings("unchecked")
                    final List<String> strings = txt.getStrings();
                    if (strings != null && !strings.isEmpty())
                    {
                        final String result = strings.get(0);
                        final String[] parts = result.split(" ?\\| ?");
                        if (parts != null && parts.length >= 1)
                            return new Long(parts[0].split(" ")[0]);
                    }
                }
    }
    catch (final Exception e)
    {
    }
    return null;
}
 
Example 47
Project: openjdk-jdk10   File: Inet6AddressSerializationTest.java   Source Code and License 5 votes vote down vote up
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 48
Project: open-rmbt   File: Helperfunctions.java   Source Code and License 5 votes vote down vote up
public static String filterIP(final InetAddress inetAddress)
{
    try
    {
        final String ipVersion;
        if (inetAddress instanceof Inet4Address)
            ipVersion = "ipv4";
        else if (inetAddress instanceof Inet6Address)
            ipVersion = "ipv6";
        else
            ipVersion = "ipv?";
        
        if (inetAddress.isAnyLocalAddress())
            return "wildcard";
        if (inetAddress.isSiteLocalAddress())
            return "site_local_" + ipVersion;
        if (inetAddress.isLinkLocalAddress())
            return "link_local_" + ipVersion;
        if (inetAddress.isLoopbackAddress())
            return "loopback_" + ipVersion;
        return inetAddress.getHostAddress();
    }
    catch (final IllegalArgumentException e)
    {
        return "illegal_ip";
    }
}
 
Example 49
Project: OpenJSharp   File: InitialToken.java   Source Code and License 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 50
Project: LiquidFortressPacketAnalyzer   File: IpPacketProcessor.java   Source Code and License 5 votes vote down vote up
public static void processIpv6Packet(Packet packet, PcapFileSummary pcapFileSummary, PacketInfo packetInfo, Mode mode) {
    if (packet == null) {
        return; // skip empty packets
    }
    try {
        log.trace("Converting to IPv6 packet");
        IpV6Packet ipV6Packet = IpV6Packet.newPacket(packet.getRawData(), 0, packet.length());
        IpV6Packet.IpV6Header ipV6Header = ipV6Packet.getHeader();
        Inet6Address sourceAddress = ipV6Header.getSrcAddr();
        Inet6Address destAddress = ipV6Header.getDstAddr();
        if (mode == Mode.POSSIBLE_ATTACKS_ANALYSIS) {
            //pcapFileSummary.ipMacTracker.query(sourceAddress.getHostAddress(), sourceMac.toString());
        }
        packetInfo.put(PacketInfo.SOURCE_ADDRESS, sourceAddress.getHostAddress());
        packetInfo.put(PacketInfo.DESTINATION_ADDRESS, destAddress.getHostAddress());
        log.trace("Adding IPv6 addresses to set:  source: " + sourceAddress.getHostAddress() + ", dest: " + destAddress.getHostAddress());
        pcapFileSummary.uniqueIpAddresses.add(sourceAddress.getHostAddress());
        pcapFileSummary.uniqueIpAddresses.add(destAddress.getHostAddress());
        IpNumber ipNumber = ipV6Header.getProtocol();
        packetInfo.put(PacketInfo.IP_PROTOCOL, ipNumber.toString());
        pcapFileSummary.ipProtocolCounter.increment(ipNumber);
        Packet payload = ipV6Packet.getPayload();
        if (ipNumber == IpNumber.ICMPV4) {
            IcmpPacketProcessor.processIcmpv4Packet(payload, pcapFileSummary, packetInfo, mode);
        } else if (ipNumber == IpNumber.ICMPV6) {
            IcmpPacketProcessor.processIcmpv6Packet(payload, pcapFileSummary, packetInfo, mode);
        } else if (ipNumber == IpNumber.TCP) {
            TcpPacketProcessor.processTcpPacket(payload, pcapFileSummary, packetInfo, mode);
        } else if (ipNumber == IpNumber.UDP) {
            UdpPacketProcessor.processUdpPacket(payload, pcapFileSummary, packetInfo, mode);
        } else {
            log.trace("Skipping packet: " + payload);
        }
    } catch (IllegalRawDataException e) {
        log.error("Exception occurred while processing a packet. Exception was: " + e);
    }
}
 
Example 51
Project: cyberduck   File: ProxySocketFactoryTest.java   Source Code and License 5 votes vote down vote up
@Test
@Ignore
public void testDefaultNetworkInterfaceForIP6Address() throws Exception {
    assertEquals(InetAddress.getByName("::1"), InetAddress.getByName("::1%en0"));
    // Bug. Defaults to awdl0 on OS X
    assertEquals(((Inet6Address) InetAddress.getByName("::1")).getScopeId(),
            ((Inet6Address) InetAddress.getByName("::1%en0")).getScopeId());
}
 
Example 52
Project: openNaEF   File: SimulationArchiveImpl.java   Source Code and License 5 votes vote down vote up
public String getTargetBy(InetAddress inetAddress) {
    String target = inetAddress.getHostAddress();
    if (inetAddress instanceof Inet6Address) {
        target = target.replace(':', '-');
    }
    return target;
}
 
Example 53
Project: RISE-V2G   File: MiscUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Determines the link-local IPv6 address which is configured on the network interface provided
 * in the properties file.
 * @return The link-local address given as a String
 */
public static Inet6Address getLinkLocalAddress() {
	String networkInterfaceConfig = getPropertyValue("network.interface").toString();
	
	NetworkInterface nif = null;
	
	try {
		if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
			nif = NetworkInterface.getByIndex(Integer.parseInt(networkInterfaceConfig));
		} else {
			nif = NetworkInterface.getByName(networkInterfaceConfig);
		}
		Enumeration<InetAddress> inetAddresses = nif.getInetAddresses();
		
		while (inetAddresses.hasMoreElements()) {
			InetAddress inetAddress = inetAddresses.nextElement();
			
			if (inetAddress.getClass() == Inet6Address.class && inetAddress.isLinkLocalAddress()) {
				return (Inet6Address) inetAddress;
			}
		}
		
		getLogger().fatal("No IPv6 link-local address found on the network interface '" +
				nif.getDisplayName() + "' configured in the properties file");
	} catch (SocketException e) {
		getLogger().fatal("SocketException while trying to get network interface for configured name " +
						  networkInterfaceConfig + "'", e); 
	} catch (NullPointerException | NumberFormatException e2) {
		getLogger().fatal("No network interface for configured network interface index '" + 
						  networkInterfaceConfig + "' found");
	}
	
	return null;
}
 
Example 54
Project: aidos-node   File: PD.java   Source Code and License 5 votes vote down vote up
public static ipType getIpTypeForAddress(InetAddress address) {
	if (address instanceof Inet4Address) {
		return ipType.ipv4;
	}
	if (address instanceof Inet6Address) {
		return ipType.ipv6;
	}
	log.warn("Couldn't identify ipType for address.");
	return null;
}
 
Example 55
Project: openjdk-jdk10   File: Inet6AddressSerializationTest.java   Source Code and License 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 56
Project: datatree-adapters   File: JsonFlex.java   Source Code and License 5 votes vote down vote up
public void addDefaultSerializers(TypeTransformerMap map) {

		// InetAddress
		addSerializer(map, InetAddress.class, (value, ctx) -> {
			ctx.writeQuoted(value.getCanonicalHostName());
		});
		addSerializer(map, Inet4Address.class, (value, ctx) -> {
			ctx.writeQuoted(value.getCanonicalHostName());
		});
		addSerializer(map, Inet6Address.class, (value, ctx) -> {
			ctx.writeQuoted(value.getCanonicalHostName());
		});

		// UUID
		addSerializer(map, UUID.class, (value, ctx) -> {
			ctx.write("\"");
			ctx.write(value.toString());
			ctx.write("\"");
		});

		// BASE64
		addSerializer(map, byte[].class, (value, ctx) -> {
			ctx.write("\"");
			ctx.write(BASE64.encode(value));
			ctx.write("\"");
		});

		// Date
		addSerializer(map, Date.class, (value, ctx) -> {
			if (Config.USE_TIMESTAMPS) {
				ctx.writeQuoted(DataConverterRegistry.convert(String.class, value));
			} else {
				ctx.write(Long.toString(value.getTime()));
			}
		});
	}
 
Example 57
Project: jdk8u-jdk   File: PingThis.java   Source Code and License 5 votes vote down vote up
private static boolean hasIPv6() throws Exception {
    List<NetworkInterface> nics = Collections.list(NetworkInterface
            .getNetworkInterfaces());
    for (NetworkInterface nic : nics) {
        List<InetAddress> addrs = Collections.list(nic.getInetAddresses());
        for (InetAddress addr : addrs) {
            if (addr instanceof Inet6Address)
                return true;
        }
    }

    return false;
}
 
Example 58
Project: Cybernet-VPN   File: OpenVPNService.java   Source Code and License 5 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 59
Project: Cybernet-VPN   File: NetworkSpace.java   Source Code and License 5 votes vote down vote up
public ipAddress(Inet6Address address, int mask, boolean include) {
    networkMask = mask;
    included = include;
    int s = 128;
    netAddress = BigInteger.ZERO;
    for (byte b : address.getAddress()) {
        s -= 8;
        netAddress = netAddress.add(BigInteger.valueOf((b & 0xFF)).shiftLeft(s));
    }
}
 
Example 60
Project: LotusCloud   File: NetworkTools.java   Source Code and License 5 votes vote down vote up
public static String decompressIPv6(String compressed) {
    try {
        return ((Inet6Address) InetAddress.getByName(compressed)).getHostAddress();
    } catch (UnknownHostException ex) {
        return compressed;
    }
}