java.net.Inet4Address Java Examples

The following examples show how to use java.net.Inet4Address. 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: ServerEnvUtils.java    From jeesuite-config with Apache License 2.0 6 votes vote down vote up
public static String getServerIpAddr()  {  
	if(ResourceUtils.containsProperty("spring.cloud.client.ipAddress")){
		return ResourceUtils.getProperty("spring.cloud.client.ipAddress");
	}
	if(serverIpAddr != null)return serverIpAddr;
	try {
		Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();  
		outter:while (en.hasMoreElements()) {  
			NetworkInterface i = en.nextElement();  
			for (Enumeration<InetAddress> en2 = i.getInetAddresses(); en2.hasMoreElements();) {  
				InetAddress addr = en2.nextElement();  
				if (!addr.isLoopbackAddress()) {  
					if (addr instanceof Inet4Address) {    
						serverIpAddr = addr.getHostAddress();  
						break outter;
					}  
				}  
			}  
		}  
	} catch (Exception e) {
		serverIpAddr = UNKNOW;
	}
    return serverIpAddr;  
}
 
Example #2
Source File: TCPTun.java    From finalspeed with GNU General Public License v2.0 6 votes vote down vote up
TCPTun(CapEnv capEnv,
       Inet4Address serverAddress, short serverPort,
       MacAddress srcAddress_mac, MacAddress dstAddrress_mac) {
    this.capEnv = capEnv;
    sendHandle = capEnv.sendHandle;
    this.remoteAddress = serverAddress;
    this.remotePort = serverPort;
    localAddress = capEnv.local_ipv4;
    localPort = (short) (random.nextInt(64 * 1024 - 1 - 10000) + 10000);
    Packet syncPacket = null;
    try {
        syncPacket = PacketUtils.createSync(srcAddress_mac, dstAddrress_mac, localAddress, localPort,
                serverAddress, serverPort, localStartSequence, getIdent());
        try {
            sendHandle.sendPacket(syncPacket);
            localSequence = localStartSequence + 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
    } catch (Exception e1) {
        e1.printStackTrace();
    }
    MLog.println("发送第一次握手 " + " ident " + localIdent);
    MLog.println("" + syncPacket);

}
 
Example #3
Source File: TestInstanceManager.java    From stratosphere with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs a new test instance manager
 */
public TestInstanceManager() {

	final HardwareDescription hd = HardwareDescriptionFactory.construct(1, 1L, 1L);
	final InstanceTypeDescription itd = InstanceTypeDescriptionFactory.construct(INSTANCE_TYPE, hd, 1);
	instanceMap.put(INSTANCE_TYPE, itd);

	this.allocatedResources = new ArrayList<AllocatedResource>();
	try {
		final InstanceConnectionInfo ici = new InstanceConnectionInfo(Inet4Address.getLocalHost(), 1, 1);
		final NetworkTopology nt = new NetworkTopology();
		final TestInstance ti = new TestInstance(INSTANCE_TYPE, ici, nt.getRootNode(), nt, hd);
		this.allocatedResources.add(new AllocatedResource(ti, INSTANCE_TYPE, new AllocationID()));
	} catch (UnknownHostException e) {
		throw new RuntimeException(StringUtils.stringifyException(e));
	}
}
 
Example #4
Source File: NetworkUtils.java    From kylin with Apache License 2.0 6 votes vote down vote up
public static String getLocalIp() {
    try {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface iface = interfaces.nextElement();
            if (iface.isLoopback() || !iface.isUp() || iface.isVirtual() || iface.isPointToPoint())
                continue;
            if (iface.getName().startsWith("vboxnet"))
                continue;

            Enumeration<InetAddress> addresses = iface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress addr = addresses.nextElement();
                final String ip = addr.getHostAddress();
                if (Inet4Address.class == addr.getClass())
                    return ip;
            }
        }
    } catch (SocketException e) {
        throw new RuntimeException(e);
    }
    return null;
}
 
Example #5
Source File: Util.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns a list of all the addresses on the system.
 * @param  inclLoopback
 *         if {@code true}, include the loopback addresses
 * @param  ipv4Only
 *         it {@code true}, only IPv4 addresses will be included
 */
static List<InetAddress> getAddresses(boolean inclLoopback,
                                      boolean ipv4Only)
    throws SocketException {
    ArrayList<InetAddress> list = new ArrayList<InetAddress>();
    Enumeration<NetworkInterface> nets =
             NetworkInterface.getNetworkInterfaces();
    for (NetworkInterface netInf : Collections.list(nets)) {
        Enumeration<InetAddress> addrs = netInf.getInetAddresses();
        for (InetAddress addr : Collections.list(addrs)) {
            if (!list.contains(addr) &&
                    (inclLoopback ? true : !addr.isLoopbackAddress()) &&
                    (ipv4Only ? (addr instanceof Inet4Address) : true)) {
                list.add(addr);
            }
        }
    }

    return list;
}
 
Example #6
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,
	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 #7
Source File: DefaultHostsFileEntriesResolver.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
public InetAddress address(String inetHost, ResolvedAddressTypes resolvedAddressTypes) {
    String normalized = normalize(inetHost);
    switch (resolvedAddressTypes) {
        case IPV4_ONLY:
            return inet4Entries.get(normalized);
        case IPV6_ONLY:
            return inet6Entries.get(normalized);
        case IPV4_PREFERRED:
            Inet4Address inet4Address = inet4Entries.get(normalized);
            return inet4Address != null? inet4Address : inet6Entries.get(normalized);
        case IPV6_PREFERRED:
            Inet6Address inet6Address = inet6Entries.get(normalized);
            return inet6Address != null? inet6Address : inet4Entries.get(normalized);
        default:
            throw new IllegalArgumentException("Unknown ResolvedAddressTypes " + resolvedAddressTypes);
    }
}
 
Example #8
Source File: CommonUtils.java    From WeBASE-Front with Apache License 2.0 6 votes vote down vote up
/**
 * get server ip.
 * 
 * @return
 */
public static String getCurrentIp() {
    try {
        Enumeration<NetworkInterface> networkInterfaces =
                NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface ni = networkInterfaces.nextElement();
            Enumeration<InetAddress> nias = ni.getInetAddresses();
            while (nias.hasMoreElements()) {
                InetAddress ia = nias.nextElement();
                if (!ia.isLinkLocalAddress() && !ia.isLoopbackAddress()
                        && ia instanceof Inet4Address) {
                    return ia.getHostAddress();
                }
            }
        }
    } catch (SocketException e) {
        log.error("getCurrentIp error.");
    }
    return null;
}
 
Example #9
Source File: MockUpnpServiceConfiguration.java    From DroidDLNA with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected NetworkAddressFactory createNetworkAddressFactory(int streamListenPort) {
    // We are only interested in 127.0.0.1
    return new NetworkAddressFactoryImpl(streamListenPort) {
        @Override
        protected boolean isUsableNetworkInterface(NetworkInterface iface) throws Exception {
            return (iface.isLoopback());
        }

        @Override
        protected boolean isUsableAddress(NetworkInterface networkInterface, InetAddress address) {
            return (address.isLoopbackAddress() && address instanceof Inet4Address);
        }

    };
}
 
Example #10
Source File: IPDeviceReadDataTest.java    From xbee-java with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Test method for {@link com.digi.xbee.api.IPDevice#readIPDataPacket(Inet4Address, int))}.
 * 
 * @throws Exception 
 */
@Test
public final void testReadIPDataPacketNotIPTimeout() throws Exception {
	// Setup the resources for the test.
	Mockito.doAnswer(new Answer<XBeePacket>() {
		public XBeePacket answer(InvocationOnMock invocation) throws Exception {
			return null;
		}
	}).when(mockXBeePacketsQueue).getFirstIPDataPacket(Mockito.anyInt());
	
	// Call the method under test.
	IPMessage message = Whitebox.invokeMethod(ipDevice, "readIPDataPacket", (Inet4Address)null, 100);
	
	// Verify the result.
	assertThat("Message must be null", message, is(equalTo(null)));
	
	Mockito.verify(mockXBeePacketsQueue).getFirstIPDataPacket(100);
}
 
Example #11
Source File: Utils.java    From reef with Apache License 2.0 6 votes vote down vote up
@Override
public int compare(final Inet4Address aa, final Inet4Address ba) {
  final byte[] a = aa.getAddress();
  final byte[] b = ba.getAddress();
  // local subnet comes after all else.
  if (a[0] == 127 && b[0] != 127) {
    return 1;
  }
  if (a[0] != 127 && b[0] == 127) {
    return -1;
  }
  for (int i = 0; i < 4; i++) {
    if (a[i] < b[i]) {
      return -1;
    }
    if (a[i] > b[i]) {
      return 1;
    }
  }
  return 0;
}
 
Example #12
Source File: LocalManagedDns.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
public InetAddress[] lookupAllHostAddr( String name )
        throws UnknownHostException
{
    String log = "[CDNS] Lookup request";
    String ip = NAMES.get( name );
    InetAddress[] result = new InetAddress[ 0 ];
    if ( ip != null && ip.length() > 0 ) {
        log += " on managed name (" + name + ")";
        byte[] ipBytes = ipStringToBytes( ip );
        result = new InetAddress[]{ Inet4Address.getByAddress( ipBytes ) };
    } else {
        log += " on non-managed name (" + name + ")";
        result = DEFAULT_DNS.lookupAllHostAddr( name );
    }
    return result;
}
 
Example #13
Source File: Util.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns a list of all the addresses on the system.
 * @param  inclLoopback
 *         if {@code true}, include the loopback addresses
 * @param  ipv4Only
 *         it {@code true}, only IPv4 addresses will be included
 */
static List<InetAddress> getAddresses(boolean inclLoopback,
                                      boolean ipv4Only)
    throws SocketException {
    ArrayList<InetAddress> list = new ArrayList<InetAddress>();
    Enumeration<NetworkInterface> nets =
             NetworkInterface.getNetworkInterfaces();
    for (NetworkInterface netInf : Collections.list(nets)) {
        Enumeration<InetAddress> addrs = netInf.getInetAddresses();
        for (InetAddress addr : Collections.list(addrs)) {
            if (!list.contains(addr) &&
                    (inclLoopback ? true : !addr.isLoopbackAddress()) &&
                    (ipv4Only ? (addr instanceof Inet4Address) : true)) {
                list.add(addr);
            }
        }
    }

    return list;
}
 
Example #14
Source File: InterfaceTest.java    From JavaLinuxNet with Apache License 2.0 6 votes vote down vote up
@Test
public void testInterfacesetAddress() throws libc.ErrnoException, UnknownHostException {
    libc.sockaddr_in originalAddress= linuxutils.ioctl_SIOCGIFADDR(device);
    logger.info("original {}", originalAddress);
    InetAddress ipv4= Inet4Address.getByName("127.0.0.4");
    libc.sockaddr_in address= new libc.sockaddr_in(ipv4);
    linuxutils.ioctl_SIOCSIFADDR(device,address);
    address= linuxutils.ioctl_SIOCGIFADDR(device);
    logger.info("IPv4 sockaddr_in: {}", Hexdump.bytesToHex(address.array(), address.array().length));
    logger.info("{}", address);
    Assert.assertEquals(0, address.port);
    Assert.assertEquals(0x7f000004, address.address);
    Assert.assertEquals(0x02,address.family);
    logger.info("{}", address.toInetAddress());
    logger.info("{}", address.toInetSocketAddress());
    linuxutils.ioctl_SIOCSIFADDR(device,new libc.sockaddr_in(0x7f000003,(short)0,socket.AF_INET));
}
 
Example #15
Source File: OpentrackerLiveSync.java    From mldht with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public void start(Collection<DHT> dhts, ConfigReader config) {
	try {
		channel = DatagramChannel.open(StandardProtocolFamily.INET);
		channel.setOption(StandardSocketOptions.IP_MULTICAST_TTL, 1);
		channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
		// we only need to send, not to receive, so need to bind to a specific port
		channel.bind(new InetSocketAddress(0));
		channel.connect(new InetSocketAddress(InetAddress.getByAddress(new byte[] {(byte) 224,0,23,5}), 9696));
	} catch (IOException e) {
		e.printStackTrace();
		return;
	}
	
	t.setDaemon(true);
	t.setName("opentracker-sync");
	t.start();
	
	// OT-sync only supports ipv4 atm
	dhts.stream().filter(d -> d.getType().PREFERRED_ADDRESS_TYPE == Inet4Address.class).forEach(d -> {
		d.addIncomingMessageListener(this::incomingPacket);
	});

}
 
Example #16
Source File: Util.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns a list of all the addresses on the system.
 * @param  inclLoopback
 *         if {@code true}, include the loopback addresses
 * @param  ipv4Only
 *         it {@code true}, only IPv4 addresses will be included
 */
static List<InetAddress> getAddresses(boolean inclLoopback,
                                      boolean ipv4Only)
    throws SocketException {
    ArrayList<InetAddress> list = new ArrayList<InetAddress>();
    Enumeration<NetworkInterface> nets =
             NetworkInterface.getNetworkInterfaces();
    for (NetworkInterface netInf : Collections.list(nets)) {
        Enumeration<InetAddress> addrs = netInf.getInetAddresses();
        for (InetAddress addr : Collections.list(addrs)) {
            if (!list.contains(addr) &&
                    (inclLoopback ? true : !addr.isLoopbackAddress()) &&
                    (ipv4Only ? (addr instanceof Inet4Address) : true)) {
                list.add(addr);
            }
        }
    }

    return list;
}
 
Example #17
Source File: IpUtils.java    From youqu_master with Apache License 2.0 6 votes vote down vote up
/**
 * 获取ip地址方法
 * @return
 */
public static String GetHostIp() {
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface
                .getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> ipAddr = intf.getInetAddresses(); ipAddr
                    .hasMoreElements();) {
                InetAddress inetAddress = ipAddr.nextElement();
                if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                    //if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet6Address) {
                    return inetAddress.getHostAddress().toString();
                }

            }
        }
    } catch (SocketException ex) {
    } catch (Exception e) {
    }
    return null;
}
 
Example #18
Source File: Hello.java    From blog_demos with Apache License 2.0 6 votes vote down vote up
public static List<Inet4Address> getLocalIp4AddressFromNetworkInterface() throws SocketException {
    List<Inet4Address> addresses = new ArrayList<>(1);
    Enumeration e = NetworkInterface.getNetworkInterfaces();
    if (e == null) {
        return addresses;
    }
    while (e.hasMoreElements()) {
        NetworkInterface n = (NetworkInterface) e.nextElement();
        if (!isValidInterface(n)) {
            continue;
        }
        Enumeration ee = n.getInetAddresses();
        while (ee.hasMoreElements()) {
            InetAddress i = (InetAddress) ee.nextElement();
            if (isValidAddress(i)) {
                addresses.add((Inet4Address) i);
            }
        }
    }
    return addresses;
}
 
Example #19
Source File: WifiDisplayController.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private static Inet4Address getInterfaceAddress(WifiP2pGroup info) {
    NetworkInterface iface;
    try {
        iface = NetworkInterface.getByName(info.getInterface());
    } catch (SocketException ex) {
        Slog.w(TAG, "Could not obtain address of network interface "
                + info.getInterface(), ex);
        return null;
    }

    Enumeration<InetAddress> addrs = iface.getInetAddresses();
    while (addrs.hasMoreElements()) {
        InetAddress addr = addrs.nextElement();
        if (addr instanceof Inet4Address) {
            return (Inet4Address)addr;
        }
    }

    Slog.w(TAG, "Could not obtain address of network interface "
            + info.getInterface() + " because it had no IPv4 addresses.");
    return null;
}
 
Example #20
Source File: Utils.java    From BetterBackdoor with MIT License 6 votes vote down vote up
/**
 * If {@code ipType} is "internal", returns the internal IP address of the
 * current machine. Otherwise, if {@code ipType} is "external", returns the
 * external IP address of the current machine.
 *
 * @param ipType type of IP address to return
 * @return either the internal or external IP address of the current machine
 * @throws IOException
 */
public static String getIP(String ipType) throws IOException {
	String ret = null;
	if (ipType.equals("internal")) {
		Enumeration<NetworkInterface> majorInterfaces = NetworkInterface.getNetworkInterfaces();
		while (majorInterfaces.hasMoreElements()) {
			NetworkInterface inter = majorInterfaces.nextElement();
			for (Enumeration<InetAddress> minorInterfaces = inter.getInetAddresses(); minorInterfaces
					.hasMoreElements(); ) {
				InetAddress add = minorInterfaces.nextElement();
				if (!add.isLoopbackAddress())
					if (add instanceof Inet4Address) {
						ret = add.getHostAddress();
						break;
					}
			}
		}
	} else if (ipType.equals("external")) {
		URL checkIP = new URL("http://checkip.amazonaws.com");
		BufferedReader in = new BufferedReader(new InputStreamReader(checkIP.openStream()));
		String ip = in.readLine();
		in.close();
		ret = ip;
	}
	return ret;
}
 
Example #21
Source File: IPUtil.java    From peer-os with Apache License 2.0 6 votes vote down vote up
public static Set<String> getLocalIps() throws SocketException
{
    Set<String> localIps = Sets.newHashSet();
    Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();

    while ( netInterfaces.hasMoreElements() )
    {
        NetworkInterface networkInterface = netInterfaces.nextElement();
        Enumeration<InetAddress> addressEnumeration = networkInterface.getInetAddresses();
        while ( addressEnumeration.hasMoreElements() )
        {
            InetAddress address = addressEnumeration.nextElement();
            if ( address instanceof Inet4Address )
            {
                localIps.add( address.getHostAddress() );
            }
        }
    }

    return localIps;
}
 
Example #22
Source File: SocketInitiator.java    From nv-websocket-client with Apache License 2.0 5 votes vote down vote up
public Socket establish(InetAddress[] addresses) throws Exception
{
    // Create socket future.
    SocketFuture future = new SocketFuture();

    // Create socket racer for each IP address.
    List<SocketRacer> racers = new ArrayList<SocketRacer>(addresses.length);
    int delay = 0;
    Signal startSignal = null;
    for (InetAddress address: addresses)
    {
        // Check if the mode requires us to skip this address.
        if (mMode == DualStackMode.IPV4_ONLY && !(address instanceof Inet4Address)
            || mMode == DualStackMode.IPV6_ONLY && !(address instanceof Inet6Address))
        {
            continue;
        }

        // Increase the *happy eyeballs* delay (see RFC 6555, sec 5.5).
        delay += mFallbackDelay;

        // Create the *done* signal which acts as a *start* signal for the subsequent racer.
        Signal doneSignal = new Signal(delay);

        // Create racer to establish the socket.
        SocketAddress socketAddress = new InetSocketAddress(address, mAddress.getPort());
        SocketRacer racer = new SocketRacer(
                future, mSocketFactory, socketAddress, mServerNames, mConnectTimeout,
                startSignal, doneSignal);
        racers.add(racer);

        // Replace *start* signal with this racer's *done* signal.
        startSignal = doneSignal;
    }

    // Wait until one of the sockets has been established, or all failed with an exception.
    return future.await(racers);
}
 
Example #23
Source File: Inet4AddressValueHandler.java    From PgBulkInsert with MIT License 5 votes vote down vote up
@Override
protected void internalHandle(DataOutputStream buffer, final Inet4Address value) throws Exception {
    buffer.writeInt(8);

    buffer.writeByte(IPv4);
    buffer.writeByte(MASK);
    buffer.writeByte(IS_CIDR);

    byte[] inet4AddressBytes = value.getAddress();

    buffer.writeByte(inet4AddressBytes.length);
    buffer.write(inet4AddressBytes);
}
 
Example #24
Source File: InitialToken.java    From jdk8u60 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 #25
Source File: LinkProperties.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Evaluate whether the {@link InetAddress} is considered reachable.
 *
 * @return {@code true} if the given {@link InetAddress} is considered reachable,
 *         {@code false} otherwise.
 * @hide
 */
public boolean isReachable(InetAddress ip) {
    final List<RouteInfo> allRoutes = getAllRoutes();
    // If we don't have a route to this IP address, it's not reachable.
    final RouteInfo bestRoute = RouteInfo.selectBestRoute(allRoutes, ip);
    if (bestRoute == null) {
        return false;
    }

    // TODO: better source address evaluation for destination addresses.

    if (ip instanceof Inet4Address) {
        // For IPv4, it suffices for now to simply have any address.
        return hasIPv4AddressOnInterface(bestRoute.getInterface());
    } else if (ip instanceof Inet6Address) {
        if (ip.isLinkLocalAddress()) {
            // For now, just make sure link-local destinations have
            // scopedIds set, since transmits will generally fail otherwise.
            // TODO: verify it matches the ifindex of one of the interfaces.
            return (((Inet6Address)ip).getScopeId() != 0);
        }  else {
            // For non-link-local destinations check that either the best route
            // is directly connected or that some global preferred address exists.
            // TODO: reconsider all cases (disconnected ULA networks, ...).
            return (!bestRoute.hasGateway() || hasGlobalIPv6Address());
        }
    }

    return false;
}
 
Example #26
Source File: TXIPv4PacketTest.java    From xbee-java with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Test method for {@link com.digi.xbee.api.packet.ip.TXIPv4Packet#setDestAddress(Inet4Address)}.
 *
 * @throws Exception
 */
@Test
public final void testSetDestAddressNotNull() throws Exception {
	// Set up the resources for the test.
	TXIPv4Packet packet = new TXIPv4Packet(frameID, destAddress, destPort, sourcePort, protocol, transmitOptions, data);

	Inet4Address newAddress = (Inet4Address) Inet4Address.getByName("192.168.1.30");

	// Call the method under test.
	packet.setDestAddress(newAddress);

	// Verify the result.
	assertThat("Dest address is not the expected one", packet.getDestAddress(), is(equalTo(newAddress)));
}
 
Example #27
Source File: AnnounceGroupChannel.java    From bt with Apache License 2.0 5 votes vote down vote up
private synchronized DatagramChannel getChannel() throws IOException {
    if (channel == null || !channel.isOpen()) {
        if (shutdown.get()) {
            throw new IllegalStateException("Channel has been shut down");
        }
        ProtocolFamily protocolFamily = InternetProtocolUtils.getProtocolFamily(group.getAddress().getAddress());
        DatagramChannel _channel = selector.provider().openDatagramChannel(protocolFamily);
        _channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
        // bind to any-local before setting TTL
        int port = group.getAddress().getPort();
        if (protocolFamily == StandardProtocolFamily.INET) {
            _channel.bind(new InetSocketAddress(Inet4Address.getByName("0.0.0.0"), port));
        } else {
            _channel.bind(new InetSocketAddress(Inet6Address.getByName("[::]"), port));
        }
        int timeToLive = group.getTimeToLive();
        if (timeToLive != 1) {
            _channel.setOption(StandardSocketOptions.IP_MULTICAST_TTL, timeToLive);
        }

        for (NetworkInterface iface : networkInterfaces) {
            _channel.join(group.getAddress().getAddress(), iface);
        }

        _channel.configureBlocking(false);
        channel = _channel;
    }
    return channel;
}
 
Example #28
Source File: InetAddressTest.java    From j2objc with 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 #29
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 #30
Source File: HostAddress.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private int getAddrType(InetAddress inetAddress) {
    int addressType = 0;
    if (inetAddress instanceof Inet4Address)
        addressType = Krb5.ADDRTYPE_INET;
    else if (inetAddress instanceof Inet6Address)
        addressType = Krb5.ADDRTYPE_INET6;
    return (addressType);
}