Java Code Examples for java.net.Inet4Address

The following are top voted examples for showing how to use java.net.Inet4Address. 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: googles-monorepo-demo   File: InetAddresses.java   Source Code and License 6 votes vote down vote up
/**
 * Examines the Inet6Address to extract the embedded IPv4 client address if the InetAddress is an
 * IPv6 address of one of the specified address types that contain an embedded IPv4 address.
 *
 * <p>NOTE: ISATAP addresses are explicitly excluded from this method due to their trivial
 * spoofability. With other transition addresses spoofing involves (at least) infection of one's
 * BGP routing table.
 *
 * @param ip {@link Inet6Address} to be examined for embedded IPv4 client address
 * @return {@link Inet4Address} of embedded IPv4 client address
 * @throws IllegalArgumentException if the argument does not have a valid embedded IPv4 address
 */
public static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip) {
  if (isCompatIPv4Address(ip)) {
    return getCompatIPv4Address(ip);
  }

  if (is6to4Address(ip)) {
    return get6to4IPv4Address(ip);
  }

  if (isTeredoAddress(ip)) {
    return getTeredoInfo(ip).getClient();
  }

  throw formatIllegalArgumentException("'%s' has no embedded IPv4 address.", toAddrString(ip));
}
 
Example 2
Project: incubator-netbeans   File: NetworkSettingsTest.java   Source Code and License 6 votes vote down vote up
public void testIsAuthenticationDialogSuppressed() throws Exception {
    final boolean[] suppressed = new boolean[1];
    Authenticator.setDefault(new Authenticator() {

        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            suppressed[0] = NetworkSettings.isAuthenticationDialogSuppressed();
            return super.getPasswordAuthentication();
        }
    });

    Callable<Void> callable = new Callable<Void>() {

        @Override
        public Void call() throws Exception {
            Authenticator.requestPasswordAuthentication("wher.ev.er", Inet4Address.getByName("1.2.3.4"), 1234, "http", null, "http");
            return null;
        }
    };
    NetworkSettings.suppressAuthenticationDialog(callable);
    assertTrue(suppressed[0]);
}
 
Example 3
Project: incubator-netbeans   File: IpAddressUtilsFilter.java   Source Code and License 6 votes vote down vote up
protected static InetAddress pickInetAddress(Iterable<InetAddress> sortedList, IpAddressUtils.IpTypePreference ipTypePref) {
    IpAddressUtils.IpTypePreference pref = getIpTypePreferenceResolved(ipTypePref);
    for (InetAddress ipAddress : sortedList) {
        if (pref == IpAddressUtils.IpTypePreference.ANY_IPV4_PREF  || pref == IpAddressUtils.IpTypePreference.ANY_IPV6_PREF) {
            return ipAddress;
        }
        if (ipAddress instanceof Inet4Address) {
            if (pref == IpAddressUtils.IpTypePreference.IPV4_ONLY) {
                return ipAddress;
            }
        }
        if (ipAddress instanceof Inet6Address) {
            if (pref == IpAddressUtils.IpTypePreference.IPV6_ONLY) {
                return ipAddress;
            }
        }
    }
    return null;
}
 
Example 4
Project: incubator-netbeans   File: IpAddressUtilsFilter.java   Source Code and License 6 votes vote down vote up
protected static @NonNull List<InetAddress> filterInetAddresses(Iterable<InetAddress> list, IpAddressUtils.IpTypePreference ipTypePref) {
    IpAddressUtils.IpTypePreference pref = getIpTypePreferenceResolved(ipTypePref);
    List<InetAddress> newList = new ArrayList<>();
    if (list != null) {
        for (InetAddress ipAddress : list) {
            if (pref == IpAddressUtils.IpTypePreference.ANY_IPV4_PREF || pref == IpAddressUtils.IpTypePreference.ANY_IPV6_PREF) {
                newList.add(ipAddress);
            } else {
                if ((ipAddress instanceof Inet4Address) && (pref == IpAddressUtils.IpTypePreference.IPV4_ONLY)) {
                    newList.add(ipAddress);
                }
                if ((ipAddress instanceof Inet6Address) && (pref == IpAddressUtils.IpTypePreference.IPV6_ONLY)) {
                    newList.add(ipAddress);
                }
            }
        }
    }
    if (pref == IpAddressUtils.IpTypePreference.ANY_IPV4_PREF) {
        IpAddressUtils.sortIpAddressesShallow(newList,true);
    }
    if (pref == IpAddressUtils.IpTypePreference.ANY_IPV6_PREF) {
        IpAddressUtils.sortIpAddressesShallow(newList,false);
    }
    return newList;
}
 
Example 5
Project: MyFire   File: IpUtils.java   Source Code and License 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 6
Project: aos-FileCoreLibrary   File: ArchosUtils.java   Source Code and License 6 votes vote down vote up
public static String getIpAddress() {
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress() && (inetAddress instanceof Inet4Address)) { // we get both ipv4 and ipv6, we want ipv4
                    return inetAddress.getHostAddress();
                }
            }
        }
    } catch (SocketException e) {
        Log.e(TAG,"getIpAddress", e);
    }

    return null;
}
 
Example 7
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 8
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 9
Project: AndroidDevSamples   File: NetworkUtil.java   Source Code and License 6 votes vote down vote up
public static String getIpv4Address() {
    try {
        for (Enumeration<NetworkInterface> enNetI = NetworkInterface.getNetworkInterfaces(); enNetI.hasMoreElements(); ) {
            NetworkInterface netI = enNetI.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = netI.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (inetAddress instanceof Inet4Address && !inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress();
                }
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }
    return "";
}
 
Example 10
Project: jdk8u-jdk   File: Util.java   Source Code and License 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 11
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 12
Project: kubernetes-client   File: Util.java   Source Code and License 6 votes vote down vote up
public static String getLocalIpAddress() {
    try {
        String localIpAddress = Collections.list(NetworkInterface.getNetworkInterfaces()).stream()
                .flatMap(networkInterface -> Collections.list(networkInterface.getInetAddresses()).stream())
                .filter(inetAddress -> inetAddress instanceof Inet4Address && inetAddress.getAddress()[0] != 127)
                .map(InetAddress::getHostAddress)
                .findFirst()
                .orElseThrow(AssertionError::new);

        logger.debug("localIpAddress: {}", localIpAddress); // TODO not even in debug.

        return localIpAddress;
    } catch (SocketException e) {
        // should never happen
        throw new AssertionError();
    }
}
 
Example 13
Project: jaer   File: SpiNNaker_InterfaceFactory.java   Source Code and License 6 votes vote down vote up
private void pingButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pingButtonActionPerformed
       String host = hostTF.getText();
     try {
        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        InetAddress adr = Inet4Address.getByName(host);
        try{
            adr.isReachable(3000);
            JOptionPane.showMessageDialog(this, host+" is reachable, but it may not be the SpiNNaker!");
        }catch(IOException notReachable){
            JOptionPane.showMessageDialog(this, host+" is not reachable: "+notReachable.toString(), "Not reachable", JOptionPane.WARNING_MESSAGE);
        }
    } catch (UnknownHostException ex) {
              JOptionPane.showMessageDialog(this, host+" is unknown host: "+ex.toString(), "Host not found", JOptionPane.WARNING_MESSAGE);
    } finally {
        setCursor(Cursor.getDefaultCursor());
    }

}
 
Example 14
Project: jwala   File: ResourceServiceImplTest.java   Source Code and License 6 votes vote down vote up
@Before
public void setup() throws Exception {
    System.setProperty(ApplicationProperties.PROPERTIES_ROOT_PATH, new File(".").getAbsolutePath() + "/src/test/resources");
    PowerMockito.mockStatic(JwalaUtils.class);
    PowerMockito.when(JwalaUtils.getHostAddress("testServer")).thenReturn(Inet4Address.getLocalHost().getHostAddress());
    PowerMockito.when(JwalaUtils.getHostAddress("testServer2")).thenReturn(Inet4Address.getLocalHost().getHostAddress());

    // It is good practice to start with a clean sheet of paper before each test that is why resourceService is
    // initialized here. This makes sure that unrelated tests don't affect each other.
    MockitoAnnotations.initMocks(this);
    reset(Config.mockHistoryFacadeService);
    reset(Config.mockJvmPersistenceService);
    reset(Config.mockWebServerPersistenceService);
    reset(Config.mockGroupPesistenceService);
    reset(Config.mockAppPersistenceService);

    when(Config.mockJvmPersistenceService.findJvmByExactName(eq("someJvm"))).thenReturn(mock(Jvm.class));
    when(Config.mockRepositoryService.upload(anyString(), any(InputStream.class))).thenReturn("thePath");
}
 
Example 15
Project: url-classifier   File: Authority.java   Source Code and License 6 votes vote down vote up
/** */
private Authority(
    Optional<String> userName, Optional<String> password,
    Optional<Object> host, int portOrNegOne,
    IDNA.Info info) {
  if (host.isPresent()) {
    Object hostObj = host.get();
    Preconditions.checkArgument(
        hostObj instanceof InternetDomainName
        || hostObj instanceof Inet4Address
        || hostObj instanceof Inet6Address,
        "Invalid host", hostObj);
  }

  this.userName = userName;
  this.password = password;
  this.host = host;
  this.portOrNegOne = portOrNegOne;
  this.info = info;
}
 
Example 16
Project: openjdk-jdk10   File: NetworkConfiguration.java   Source Code and License 6 votes vote down vote up
/**
 * Return a NetworkConfiguration instance.
 */
public static NetworkConfiguration probe() throws IOException {
    Map<NetworkInterface, List<Inet4Address>> ip4Interfaces = new HashMap<>();
    Map<NetworkInterface, List<Inet6Address>> ip6Interfaces = new HashMap<>();

    List<NetworkInterface> nifs = list(getNetworkInterfaces());
    for (NetworkInterface nif : nifs) {
        // ignore interfaces that are down
        if (!nif.isUp() || nif.isPointToPoint()) {
            continue;
        }

        List<Inet4Address> ip4Addresses = new LinkedList<>();
        List<Inet6Address> ip6Addresses = new LinkedList<>();
        ip4Interfaces.put(nif, ip4Addresses);
        ip6Interfaces.put(nif, ip6Addresses);
        for (InetAddress addr : list(nif.getInetAddresses())) {
            if (addr instanceof Inet4Address) {
                ip4Addresses.add((Inet4Address) addr);
            } else if (addr instanceof Inet6Address) {
                ip6Addresses.add((Inet6Address) addr);
            }
        }
    }
    return new NetworkConfiguration(ip4Interfaces, ip6Interfaces);
}
 
Example 17
Project: jdk8u-jdk   File: Util.java   Source Code and License 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 18
Project: Hotspot-master-devp   File: AppUtils.java   Source Code and License 6 votes vote down vote up
/**
 * <code>getLocalIPAddress</code>
 * @description: TODO(获得本机的IP地址) 
 * @return
 * @throws SocketException
 * @since   2014-4-16    yourname
 */
public static String getLocalIPAddress(){ 
    try{
   	    for(Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();en.hasMoreElements();){ 
   	        NetworkInterface intf = en.nextElement();
   	        for(Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();){ 
   	            InetAddress inetAddress = enumIpAddr.nextElement(); 
   	            if(android.os.Build.VERSION.SDK_INT>10){
   	                /**android 4.0以上版本*/
   	                if(!inetAddress.isLoopbackAddress() && (inetAddress instanceof Inet4Address)){ 
   	                    return inetAddress.getHostAddress().toString(); 
   	                } 
   	            }else {
   	                if(!inetAddress.isLoopbackAddress()){ 
                           return inetAddress.getHostAddress().toString(); 
                       } 
   	            }
   	        } 
   	    } 
    }catch(Exception ex){
        ex.toString();
    }
    return null; 
}
 
Example 19
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 20
Project: tcc-rpg   File: TelaInicial.java   Source Code and License 6 votes vote down vote up
private static String getFirstNonLoopbackAddress(boolean preferIpv4, boolean preferIPv6) throws SocketException {
    Enumeration en = NetworkInterface.getNetworkInterfaces();
    while (en.hasMoreElements()) {
        NetworkInterface i = (NetworkInterface) en.nextElement();
        for (Enumeration en2 = i.getInetAddresses(); en2.hasMoreElements();) {
            InetAddress addr = (InetAddress) en2.nextElement();
            if (!addr.isLoopbackAddress()) {
                if (addr instanceof Inet4Address) {
                    if (preferIPv6) {
                        continue;
                    }
                    return addr.getHostAddress();
                }
                if (addr instanceof Inet6Address) {
                    if (preferIpv4) {
                        continue;
                    }
                    return addr.getHostAddress();
                }
            }
        }
    }
    return null;
}
 
Example 21
Project: guava-mock   File: InetAddresses.java   Source Code and License 6 votes vote down vote up
/**
 * Examines the Inet6Address to extract the embedded IPv4 client address if the InetAddress is an
 * IPv6 address of one of the specified address types that contain an embedded IPv4 address.
 *
 * <p>NOTE: ISATAP addresses are explicitly excluded from this method due to their trivial
 * spoofability. With other transition addresses spoofing involves (at least) infection of one's
 * BGP routing table.
 *
 * @param ip {@link Inet6Address} to be examined for embedded IPv4 client address
 * @return {@link Inet4Address} of embedded IPv4 client address
 * @throws IllegalArgumentException if the argument does not have a valid embedded IPv4 address
 */
public static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip) {
  if (isCompatIPv4Address(ip)) {
    return getCompatIPv4Address(ip);
  }

  if (is6to4Address(ip)) {
    return get6to4IPv4Address(ip);
  }

  if (isTeredoAddress(ip)) {
    return getTeredoInfo(ip).getClient();
  }

  throw formatIllegalArgumentException("'%s' has no embedded IPv4 address.", toAddrString(ip));
}
 
Example 22
Project: oneops   File: Config.java   Source Code and License 6 votes vote down vote up
/**
 * Retruns the inductor IP address (IPV4 address). If there are multiple NICs/IfAddresses, it
 * selects the first one. Openstack VMs normally has only one network interface (eth0).
 *
 * @return IPV4 address of inductor with interface name. Returns <code>null</code> if it couldn't
 * find anything.
 */
private String getInductorIPv4Addr() {
  try {
    Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();
    while (nics.hasMoreElements()) {
      NetworkInterface nic = nics.nextElement();
      if (nic.isUp() && !nic.isLoopback()) {
        Enumeration<InetAddress> addrs = nic.getInetAddresses();
        while (addrs.hasMoreElements()) {
          InetAddress add = addrs.nextElement();
          // Print only IPV4 address
          if (add instanceof Inet4Address && !add.isLoopbackAddress()) {
            // Log the first one.
            String ip = add.getHostAddress() + " (" + nic.getDisplayName() + ")";
            logger.info("Inductor IP : " + ip);
            return ip;
          }
        }
      }
    }
  } catch (Exception e) {
    logger.warn("Error getting inductor IP address", e);
    // Skip any errors
  }
  return null;
}
 
Example 23
Project: OpenJSharp   File: SdpProvider.java   Source Code and License 6 votes vote down vote up
private void convertTcpToSdpIfMatch(FileDescriptor fdObj,
                                           Action action,
                                           InetAddress address,
                                           int port)
    throws IOException
{
    boolean matched = false;
    for (Rule rule: rules) {
        if (rule.match(action, address, port)) {
            SdpSupport.convertSocket(fdObj);
            matched = true;
            break;
        }
    }
    if (log != null) {
        String addr = (address instanceof Inet4Address) ?
            address.getHostAddress() : "[" + address.getHostAddress() + "]";
        if (matched) {
            log.format("%s to %s:%d (socket converted to SDP protocol)\n", action, addr, port);
        } else {
            log.format("%s to %s:%d (no match)\n", action, addr, port);
        }
    }
}
 
Example 24
Project: openjdk-jdk10   File: SdpProvider.java   Source Code and License 6 votes vote down vote up
private void convertTcpToSdpIfMatch(FileDescriptor fdObj,
                                           Action action,
                                           InetAddress address,
                                           int port)
    throws IOException
{
    boolean matched = false;
    for (Rule rule: rules) {
        if (rule.match(action, address, port)) {
            SdpSupport.convertSocket(fdObj);
            matched = true;
            break;
        }
    }
    if (log != null) {
        String addr = (address instanceof Inet4Address) ?
            address.getHostAddress() : "[" + address.getHostAddress() + "]";
        if (matched) {
            log.format("%s to %s:%d (socket converted to SDP protocol)\n", action, addr, port);
        } else {
            log.format("%s to %s:%d (no match)\n", action, addr, port);
        }
    }
}
 
Example 25
Project: alexa-gira-bridge   File: TcpServer.java   Source Code and License 6 votes vote down vote up
public InetAddress getLocalAddress() {
	try {
		Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
		while (ifaces.hasMoreElements()) {
			NetworkInterface iface = ifaces.nextElement();
			Enumeration<InetAddress> addresses = iface.getInetAddresses();

			while (addresses.hasMoreElements()) {
				InetAddress addr = addresses.nextElement();
				if (addr instanceof Inet4Address && !addr.isLoopbackAddress()) {
					return addr;
				}
			}
		}
	} catch (SocketException se) {
		log.error("Cannot determine local ipv4 address.", se);
	}

	return null;
}
 
Example 26
Project: NSS   File: TCPTun.java   Source Code and License 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 27
Project: gnirehtet   File: TunnelServer.java   Source Code and License 6 votes vote down vote up
public TunnelServer(int port, Selector selector) throws IOException {
    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    serverSocketChannel.configureBlocking(false);
    // ServerSocketChannel.bind() requires API 24
    serverSocketChannel.socket().bind(new InetSocketAddress(Inet4Address.getLoopbackAddress(), port));

    SelectionHandler socketChannelHandler = (selectionKey) -> {
        try {
            ServerSocketChannel channel = (ServerSocketChannel) selectionKey.channel();
            acceptClient(selector, channel);
        } catch (IOException e) {
            Log.e(TAG, "Cannot accept client", e);
        }
    };
    serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT, socketChannelHandler);
}
 
Example 28
Project: XinFramework   File: SysUtils.java   Source Code and License 6 votes vote down vote up
/**
 * 获取手机ip地址
 */
public static String getPhoneIp() {
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements(); ) {
            NetworkInterface anInterface = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = anInterface.getInetAddresses(); enumIpAddr
                    .hasMoreElements(); ) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                    Log.i("IP info:"+inetAddress.getHostAddress(),"");
                    return inetAddress.getHostAddress();
                }
            }
        }
    } catch (Exception e) {
        Log.printStackTrace(e);
    }
    return "";
}
 
Example 29
Project: aidos-node   File: PD.java   Source Code and License 6 votes vote down vote up
private void setIpMode() throws Exception {
	InetAddress[] test = InetAddress.getAllByName(ipSeed);
	for (InetAddress t : test) {
		if (t instanceof Inet6Address && isPeerOnline(new InetSocketAddress((Inet6Address) t, defaultAPIport))) {
			ipMode.put(ipType.ipv6,
					isPeerRunning(new InetSocketAddress((Inet6Address) t, defaultAPIport)).orElse(""));
			log.debug("IP set to: {} (ipv6)", ipMode.get(ipType.ipv6));
			if (ipMode.get(ipType.ipv6).equals("")) {
				log.debug("Failure setting ip mode. (ipv6)");
			}
		}
		if (t instanceof Inet4Address && isPeerOnline(new InetSocketAddress((Inet4Address) t, defaultAPIport))) {
			ipMode.put(ipType.ipv4,
					isPeerRunning(new InetSocketAddress((Inet4Address) t, defaultAPIport)).orElse(""));
			log.debug("IP set to: {} (ipv4)", ipMode.get(ipType.ipv4));
			if (ipMode.get(ipType.ipv4).equals("")) {
				log.debug("Failure setting ip mode. (ipv4)");
			}
		}
	}
	if (ipMode.get(ipType.ipv4).equals("") && ipMode.get(ipType.ipv6).equals("")) {
		throw new Exception("Couldn't set ip mode. Maybe " + ipSeed + " isn't reachable.");
	}
}
 
Example 30
Project: FinalSpeed   File: CapEnv.java   Source Code and License 6 votes vote down vote up
public void createTcpTun_Client(String dstAddress,short dstPort) throws Exception{
	Inet4Address serverAddress=(Inet4Address) Inet4Address.getByName(dstAddress);
	TCPTun conn=new TCPTun(this,serverAddress,dstPort,local_mac,gateway_mac);
	tcpManager.addConnection_Client(conn);
	boolean success=false;
	for(int i=0;i<6;i++){
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		if(conn.preDataReady){
			success=true;
			break;
		}
	}
	if(success){
		tcpManager.setDefaultTcpTun(conn);
	}else {
		tcpManager.removeTun(conn);
		tcpManager.setDefaultTcpTun(null);
		throw new Exception("创建隧道失败!");
	}
}
 
Example 31
Project: letv   File: a.java   Source Code and License 6 votes vote down vote up
public static String d() {
    try {
        Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            Enumeration inetAddresses = ((NetworkInterface) networkInterfaces.nextElement()).getInetAddresses();
            while (inetAddresses.hasMoreElements()) {
                InetAddress inetAddress = (InetAddress) inetAddresses.nextElement();
                if (!inetAddress.isLoopbackAddress() && (inetAddress instanceof Inet4Address)) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (Exception e) {
        z.d();
        e.printStackTrace();
    }
    return "";
}
 
Example 32
Project: googles-monorepo-demo   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 33
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 34
Project: sstable-adaptor   File: DatabaseDescriptor.java   Source Code and License 5 votes vote down vote up
private static InetAddress getNetworkInterfaceAddress(String intf, String configName, boolean preferIPv6) throws ConfigurationException
{
    try
    {
        NetworkInterface ni = NetworkInterface.getByName(intf);
        if (ni == null)
            throw new ConfigurationException("Configured " + configName + " \"" + intf + "\" could not be found", false);
        Enumeration<InetAddress> addrs = ni.getInetAddresses();
        if (!addrs.hasMoreElements())
            throw new ConfigurationException("Configured " + configName + " \"" + intf + "\" was found, but had no addresses", false);

        /*
         * Try to return the first address of the preferred type, otherwise return the first address
         */
        InetAddress retval = null;
        while (addrs.hasMoreElements())
        {
            InetAddress temp = addrs.nextElement();
            if (preferIPv6 && temp instanceof Inet6Address) return temp;
            if (!preferIPv6 && temp instanceof Inet4Address) return temp;
            if (retval == null) retval = temp;
        }
        return retval;
    }
    catch (SocketException e)
    {
        throw new ConfigurationException("Configured " + configName + " \"" + intf + "\" caused an exception", e);
    }
}
 
Example 35
Project: monarch   File: JGAddress.java   Source Code and License 5 votes vote down vote up
@Override
public int size() {
  // length (1 bytes) + 4 bytes for port
  int tmp_size =
      Global.BYTE_SIZE + Global.SHORT_SIZE + Global.SHORT_SIZE + (2 * Global.LONG_SIZE);
  if (ip_addr != null) {
    // 4 bytes for IPv4, 20 for IPv6 (16 + 4 for scope-id)
    tmp_size += (ip_addr instanceof Inet4Address) ? 4 : 20;
  }
  return tmp_size;
}
 
Example 36
Project: africastalking-java   File: App.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws IOException {

        InetAddress host = Inet4Address.getLocalHost();
        log("\n");
        log(String.format("SDK Server: %s:%d", host.getHostAddress(), RPC_PORT));
        log(String.format("HTTP Server: %s:%d", host.getHostAddress(), HTTP_PORT));
        log("\n");

        setupAfricastalking();

        port(HTTP_PORT);
        
        staticFiles.location("/public");
        exception(Exception.class, (e, req, res) -> e.printStackTrace()); // print all exceptions

        get("/", (req, res) -> {
            Map<String, Object> data = new HashMap<>();
            data.put("req", req.pathInfo());
            return render("index", data);
        });

        // Send SMS
        post("/auth/register/:phone", (req, res) -> sms.send("Welcome to Awesome Company", "AT2FA", new String[] {req.params("phone")}), gson::toJson);

        // Send Airtime
        post("/airtime/:phone", (req, res) -> airtime.send(req.params("phone"), req.queryParams("amount")), gson::toJson);

        // Mobile Checkout
        post("/mobile/checkout/:phone", (req, res) -> payment.mobileCheckout("TestProduct", req.params("phone"), req.queryParams("amount"), null), gson::toJson);

        // Mobile B2C
        post("/mobile/b2c/:phone", (req, res) -> payment.mobileB2C("TestProduct", Arrays.asList(new Consumer("Boby", req.params("phone"), req.queryParams("amount"), Consumer.REASON_SALARY))), gson::toJson);

    }
 
Example 37
Project: incubator-netbeans   File: NbAuthenticatorTest.java   Source Code and License 5 votes vote down vote up
public void testUserInfoInUrl () throws Exception {
    NbAuthenticator.install4test();
    PasswordAuthentication auth = Authenticator.requestPasswordAuthentication("wher.ev.er", Inet4Address.getByName("1.2.3.4"), 1234, "http", null, "http",
            new URL("http://user:[email protected]/resource"), Authenticator.RequestorType.SERVER);
    
    assertNotNull(auth);
    assertEquals("user", auth.getUserName());
    assertEquals("password", new String(auth.getPassword()));
}
 
Example 38
Project: incubator-netbeans   File: NbAuthenticatorTest.java   Source Code and License 5 votes vote down vote up
public void testSupressedAuthenticator () throws Exception {
    NbAuthenticator.install4test();
    PasswordAuthentication auth =
        NetworkSettings.suppressAuthenticationDialog(new Callable<PasswordAuthentication>() {
            @Override
            public PasswordAuthentication call () throws Exception {
                return Authenticator.requestPasswordAuthentication("wher.ev.er", Inet4Address.getByName("1.2.3.4"), 1234, "http", null, "http",
                        new URL("http://user:[email protected]/resource"), Authenticator.RequestorType.SERVER);
            }
        });
    assertNull(auth);
}
 
Example 39
Project: datatree-adapters   File: XmlXStream.java   Source Code and License 5 votes vote down vote up
public void addDefaultSerializers() {

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

		// UUID
		addSerializer(mapper, UUID.class, (value) -> {
			return value.toString();
		});

		// BASE64
		addSerializer(mapper, byte[].class, (value) -> {
			return BASE64.encode(value);
		});

		// Date
		addSerializer(mapper, Date.class, (value) -> {
			if (Config.USE_TIMESTAMPS) {
				return DataConverterRegistry.convert(String.class, value);
			}
			return Long.toString(value.getTime());
		});
	}
 
Example 40
Project: HueSense   File: NetworkUtil.java   Source Code and License 5 votes vote down vote up
public static List<InetAddress> getLocalInetAddresses() throws IOException {
    List<InetAddress> ret = new ArrayList<>();

    Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
    if (networkInterfaces == null) {
        return ret;
    }

    while (networkInterfaces.hasMoreElements()) {
        NetworkInterface card = networkInterfaces.nextElement();

        if (card.isLoopback() || card.isPointToPoint() || card.isVirtual() || !card.isUp()) {
            continue;
        }

        Enumeration<InetAddress> addresses = card.getInetAddresses();
        while (addresses.hasMoreElements()) {
            InetAddress inetAddress = addresses.nextElement();
            int index = ret.size();

            if (Inet4Address.class.isInstance(inetAddress)) {
                ret.add(index, inetAddress);
            }
        }
    }

    return ret;
}
 
Example 41
Project: AgentWorkbench   File: NetworkAddresses.java   Source Code and License 5 votes vote down vote up
/**
 * Sets the {@link InetAddress}.
 * @param inetAddress the new inet address
 */
public void setInetAddress(InetAddress inetAddress) {
	this.inetAddress = inetAddress;
	if (inetAddress instanceof Inet4Address) {
		this.setInetAddressType(InetAddressType.Inet4Address);
	} else if (inetAddress instanceof Inet6Address) {
		this.setInetAddressType(InetAddressType.Inet6Address);
	} else {
		if (debug) {
			System.out.println("Found: " + this.inetAddress.getClass().getName() );
		}
	}
}
 
Example 42
Project: framework   File: AlipayUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 获取本机的网络IP
 */
public static String getLocalNetWorkIp() {
	if (localIp != null) {
		return localIp;
	}
	try {
		Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
		InetAddress ip = null;
		while (netInterfaces.hasMoreElements()) {// 遍历所有的网卡
			NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
			if (ni.isLoopback() || ni.isVirtual()) {// 如果是回环和虚拟网络地址的话继续
				continue;
			}
			Enumeration<InetAddress> addresss = ni.getInetAddresses();
			while (addresss.hasMoreElements()) {
				InetAddress address = addresss.nextElement();
				if (address instanceof Inet4Address) {// 这里暂时只获取ipv4地址
					ip = address;
					break;
				}
			}
			if (ip != null) {
				break;
			}
		}
		if (ip != null) {
			localIp = ip.getHostAddress();
		} else {
			localIp = "127.0.0.1";
		}
	} catch (Exception e) {
		localIp = "127.0.0.1";
	}
	return localIp;
}
 
Example 43
Project: sstore-soft   File: ConnectionUtil.java   Source Code and License 5 votes vote down vote up
public static String getHostnameOrAddress() {
    try {
        final InetAddress addr = InetAddress.getLocalHost();
        return addr.getHostName();
    } catch (UnknownHostException e) {
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            if (interfaces == null) {
                return "";
            }
            NetworkInterface intf = interfaces.nextElement();
            Enumeration<InetAddress> addresses = intf.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress address = addresses.nextElement();
                if (address instanceof Inet4Address) {
                    return address.getHostAddress();
                }
            }
            interfaces = NetworkInterface.getNetworkInterfaces();
            while (addresses.hasMoreElements()) {
                return addresses.nextElement().getHostAddress();
            }
            return "";
        } catch (SocketException e1) {
            return "";
        }
    }
}
 
Example 44
Project: sstore-soft   File: ConnectionUtil.java   Source Code and License 5 votes vote down vote up
public static InetAddress getLocalAddress() {
    try {
        final InetAddress addr = InetAddress.getLocalHost();
        return addr;
    } catch (UnknownHostException e) {
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            if (interfaces == null) {
                return null;
            }
            NetworkInterface intf = interfaces.nextElement();
            Enumeration<InetAddress> addresses = intf.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress address = addresses.nextElement();
                if (address instanceof Inet4Address) {
                    return address;
                }
            }
            interfaces = NetworkInterface.getNetworkInterfaces();
            while (addresses.hasMoreElements()) {
                return addresses.nextElement();
            }
            return null;
        } catch (SocketException e1) {
            return null;
        }
    }
}
 
Example 45
Project: leaf-snowflake   File: Utils.java   Source Code and License 5 votes vote down vote up
/**
 * 获得外网IP
 * @return 外网IP
 */
public static String getInternetIp(){
	if( true )
		return getIntranetIp();
	try{
		Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
		InetAddress ip = null;
		Enumeration<InetAddress> addrs;
		while (networks.hasMoreElements())
		{
			addrs = networks.nextElement().getInetAddresses();
			while (addrs.hasMoreElements())
			{
				ip = addrs.nextElement();
				if (ip != null
						&& ip instanceof Inet4Address
						&& ip.isSiteLocalAddress()
						&& !ip.getHostAddress().equals(getIntranetIp()))
				{
					return ip.getHostAddress();
				}
			}
		}

		// 如果没有外网IP,就返回内网IP
		return getIntranetIp();
	} catch(Exception e){
		throw new RuntimeException(e);
	}
}
 
Example 46
Project: aos-FileCoreLibrary   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 java.io.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(FTPCmd.EPRT, info.toString());
}
 
Example 47
Project: jwala   File: JwalaUtilsTest.java   Source Code and License 5 votes vote down vote up
@Test
/**
 * Test IP from IP
 */
public void testIPv4Address() throws UnknownHostException{
    String host = Inet4Address.getLocalHost().getHostAddress();
    assertEquals(host,JwalaUtils.getHostAddress(host));
}
 
Example 48
Project: jigsaw-payment   File: IpPortResolver.java   Source Code and License 5 votes vote down vote up
/**
 * 获取指定网卡上的ipv4地址
 * @param inetAddress
 * @return
 */
private String getIpV4Address(InetAddress inetAddress) {
    if (inetAddress == null
            || inetAddress.isLoopbackAddress()
            || inetAddress instanceof Inet6Address) {
        return null;
    }

    if (inetAddress instanceof Inet4Address) {
        return inetAddress.getHostAddress();
    }

    return null;
}
 
Example 49
Project: util   File: IPUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 从IPv4String转换为InetAddress.
 * 
 * IpString如果确定ipv4, 使用本方法减少字符分析消耗 .
 * 
 * 先字符串传换为byte[]再调getByAddress(byte[]),避免了调用getByName(ip)可能引起的DNS访问.
 */
public static Inet4Address fromIpv4String(String address) {
	byte[] bytes = ip4StringToBytes(address);
	if (bytes == null) {
		return null;
	} else {
		try {
			return (Inet4Address) Inet4Address.getByAddress(bytes);
		} catch (UnknownHostException e) {
			throw new AssertionError(e);
		}
	}
}
 
Example 50
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 51
Project: aws-sdk-java-v2   File: ConnectionUtilsComponentTest.java   Source Code and License 5 votes vote down vote up
@Test
public void proxiesAreNotUsedEvenIfPropertyIsSet() throws IOException {
    assumeTrue(Inet4Address.getLocalHost().isReachable(100));
    System.getProperties().put("http.proxyHost", "localhost");
    System.getProperties().put("http.proxyPort", String.valueOf(mockProxyServer.port()));
    HttpURLConnection connection = sut.connectToEndpoint(URI.create("http://" + Inet4Address.getLocalHost().getHostAddress() + ":" + mockServer.port()), emptyMap());

    assertThat(connection.usingProxy()).isFalse();
}
 
Example 52
Project: openvisualtraceroute   File: JNetCapTraceRoute.java   Source Code and License 5 votes vote down vote up
/**
 * Return the local IPV4 of the given device
 *
 * @param device the device
 * @return the IP
 */
public static InetAddress getIpOfDevice(final PcapIf device) {
	for (final PcapAddr addr : device.getAddresses()) {
		try {
			final InetAddress net = InetAddress.getByAddress(addr.getAddr().getData());
			if (net instanceof Inet4Address) {
				return net;
			}
		} catch (final UnknownHostException e) {
		}
	}
	return null;
}
 
Example 53
Project: Nird2   File: WanTcpPlugin.java   Source Code and License 5 votes vote down vote up
private boolean isAcceptableAddress(InetAddress a) {
	// Accept global IPv4 addresses
	boolean ipv4 = a instanceof Inet4Address;
	boolean loop = a.isLoopbackAddress();
	boolean link = a.isLinkLocalAddress();
	boolean site = a.isSiteLocalAddress();
	return ipv4 && !loop && !link && !site;
}
 
Example 54
Project: Nird2   File: LanTcpPluginTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testIncomingConnection() throws Exception {
	if (!systemHasLocalIpv4Address()) {
		System.err.println("WARNING: Skipping test, no local IPv4 address");
		return;
	}
	Callback callback = new Callback();
	Executor executor = Executors.newCachedThreadPool();
	DuplexPlugin plugin = new LanTcpPlugin(executor, backoff, callback,
			0, 0);
	plugin.start();
	// The plugin should have bound a socket and stored the port number
	assertTrue(callback.propertiesLatch.await(5, SECONDS));
	String ipPorts = callback.local.get("ipPorts");
	assertNotNull(ipPorts);
	String[] split = ipPorts.split(",");
	assertEquals(1, split.length);
	split = split[0].split(":");
	assertEquals(2, split.length);
	String addrString = split[0], portString = split[1];
	InetAddress addr = InetAddress.getByName(addrString);
	assertTrue(addr instanceof Inet4Address);
	assertFalse(addr.isLoopbackAddress());
	assertTrue(addr.isLinkLocalAddress() || addr.isSiteLocalAddress());
	int port = Integer.parseInt(portString);
	assertTrue(port > 0 && port < 65536);
	// The plugin should be listening on the port
	InetSocketAddress socketAddr = new InetSocketAddress(addr, port);
	Socket s = new Socket();
	s.connect(socketAddr, 100);
	assertTrue(callback.connectionsLatch.await(5, SECONDS));
	s.close();
	// Stop the plugin
	plugin.stop();
}
 
Example 55
Project: Nird2   File: LanTcpPluginTest.java   Source Code and License 5 votes vote down vote up
private boolean systemHasLocalIpv4Address() throws Exception {
	for (NetworkInterface i : Collections.list(
			NetworkInterface.getNetworkInterfaces())) {
		for (InetAddress a : Collections.list(i.getInetAddresses())) {
			if (a instanceof Inet4Address)
				return a.isLinkLocalAddress() || a.isSiteLocalAddress();
		}
	}
	return false;
}
 
Example 56
Project: dev-courses   File: JDBCXID.java   Source Code and License 5 votes vote down vote up
private static byte[] getLocalIp() {
    if (null == s_localIp) {
        try {
            s_localIp = Inet4Address.getLocalHost().getAddress();
        } catch (Exception ex) {
            s_localIp = new byte[]{0x7F, 0x00, 0x00, 0x01};
        }
    }
    return s_localIp;
}
 
Example 57
Project: Nird2   File: LanTcpPluginTest.java   Source Code and License 5 votes vote down vote up
private boolean systemHasLocalIpv4Address() throws Exception {
	for (NetworkInterface i : Collections.list(
			NetworkInterface.getNetworkInterfaces())) {
		for (InetAddress a : Collections.list(i.getInetAddresses())) {
			if (a instanceof Inet4Address)
				return a.isLinkLocalAddress() || a.isSiteLocalAddress();
		}
	}
	return false;
}
 
Example 58
Project: url-classifier   File: AuthorityClassifierBuilder.java   Source Code and License 5 votes vote down vote up
/**
 * Builds a classifier based on previous allow/match decisions.
 * This may be reused after a call to build and subsequent calls to
 * allow/match methods will not affect previously built classifiers.
 */
public AuthorityClassifier build() {
  ImmutableSet<Inet4Address> ipv4Set = ipv4s.build();
  ImmutableSet<Inet6Address> ipv6Set = ipv6s.build();
  ImmutableSet<InternetDomainName> domainNameSet = domainNames.build();
  HostGlobMatcher hostGlobMatcher = new HostGlobMatcher(hostGlobs.build());
  int[] allowedPortsSorted;
  {
    ImmutableSet<Integer> allowedPortIntSet = allowedPorts.build();
    int n = allowedPortIntSet.size();
    allowedPortsSorted = new int[n];
    Iterator<Integer> allowedPortIt = allowedPortIntSet.iterator();
    for (int i = 0; i < n; ++i) {
      allowedPortsSorted[i] = allowedPortIt.next();
    }
    Arrays.sort(allowedPortsSorted);
  }
  Predicate<? super Integer> portClassifier =
      allowedPortsSorted.length == 0  // No exclusion specified
      ? Predicates.alwaysTrue()
      : Predicates.alwaysFalse();
  if (this.allowedPortClassifier != null) {
    portClassifier = this.allowedPortClassifier;
  }
  UserInfoClassifier userInfoClassifier =
      this.allowedUserInfoClassifier != null
      ? this.allowedUserInfoClassifier
      : UserInfoClassifiers.NO_PASSWORD_BUT_USERNAME_IF_ALLOWED_BY_SCHEME;
  return new AuthorityClassifierImpl(
      ipv4Set,
      ipv6Set,
      domainNameSet,
      hostGlobMatcher,
      matchesAnyHost,
      allowedPortsSorted,
      portClassifier,
      userInfoClassifier);
}
 
Example 59
Project: GoPush   File: IpUtils.java   Source Code and License 5 votes vote down vote up
/***
 * 获取外网IP
 * @return
 */
public static String internetIp() {
    try {

        Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
        InetAddress inetAddress = null;
        Enumeration<InetAddress> inetAddresses = null;
        while (networks.hasMoreElements()) {
            inetAddresses = networks.nextElement().getInetAddresses();
            while (inetAddresses.hasMoreElements()) {
                inetAddress = inetAddresses.nextElement();
                if (inetAddress != null
                        && inetAddress instanceof Inet4Address
                        && !inetAddress.isSiteLocalAddress()
                        && !inetAddress.isLoopbackAddress()
                        && inetAddress.getHostAddress().indexOf(":") == -1) {
                    return inetAddress.getHostAddress();
                }
            }
        }

        return null;

    } catch (Exception e) {

        throw new RuntimeException(e);
    }
}
 
Example 60
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);
}