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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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;
}