Java 类java.net.Inet4Address 实例源码

项目:googles-monorepo-demo    文件:InetAddresses.java   
/**
 * 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));
}
项目:incubator-netbeans    文件:NetworkSettingsTest.java   
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]);
}
项目:incubator-netbeans    文件:IpAddressUtilsFilter.java   
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;
}
项目:incubator-netbeans    文件:IpAddressUtilsFilter.java   
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;
}
项目:MyFire    文件:IpUtils.java   
/**
 * 获取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;
}
项目:aos-FileCoreLibrary    文件:ArchosUtils.java   
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;
}
项目:googles-monorepo-demo    文件:InetAddresses.java   
/**
 * 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);
}
项目:BiglyBT    文件:DHTPlugin.java   
@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 );
}
项目:AndroidDevSamples    文件:NetworkUtil.java   
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 "";
}
项目:jdk8u-jdk    文件:Util.java   
/**
 * 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;
}
项目:athena    文件:IpAddress.java   
/**
 * 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);
}
项目:kubernetes-client    文件:Util.java   
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();
    }
}
项目:jaer    文件:SpiNNaker_InterfaceFactory.java   
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());
    }

}
项目:jwala    文件:ResourceServiceImplTest.java   
@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");
}
项目:url-classifier    文件:Authority.java   
/** */
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;
}
项目:openjdk-jdk10    文件:NetworkConfiguration.java   
/**
 * 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);
}
项目:jdk8u-jdk    文件:Util.java   
/**
 * 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;
}
项目:Hotspot-master-devp    文件:AppUtils.java   
/**
 * <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; 
}
项目:guava-mock    文件:InetAddresses.java   
/**
 * 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);
}
项目:tcc-rpg    文件:TelaInicial.java   
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;
}
项目:guava-mock    文件:InetAddresses.java   
/**
 * 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));
}
项目:oneops    文件:Config.java   
/**
 * 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;
}
项目:OpenJSharp    文件:SdpProvider.java   
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);
        }
    }
}
项目:openjdk-jdk10    文件:SdpProvider.java   
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);
        }
    }
}
项目:alexa-gira-bridge    文件:TcpServer.java   
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;
}
项目:NSS    文件:TCPTun.java   
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);

}
项目:gnirehtet    文件:TunnelServer.java   
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);
}
项目:XinFramework    文件:SysUtils.java   
/**
 * 获取手机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 "";
}
项目:aidos-node    文件:PD.java   
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.");
    }
}
项目:FinalSpeed    文件:CapEnv.java   
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("创建隧道失败!");
    }
}
项目:letv    文件:a.java   
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 "";
}
项目:googles-monorepo-demo    文件:InetAddresses.java   
/**
 * 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);
}
项目:datatree-adapters    文件:JsonGenson.java   
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();
}
项目:sstable-adaptor    文件:DatabaseDescriptor.java   
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);
    }
}
项目:monarch    文件:JGAddress.java   
@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;
}
项目:africastalking-java    文件:App.java   
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);

    }
项目:datatree-adapters    文件:XmlXStream.java   
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());
        });
    }
项目:HueSense    文件:NetworkUtil.java   
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;
}