Java 类java.net.NetworkInterface 实例源码

项目:jdk8u-jdk    文件:JdpBroadcaster.java   
/**
 * Create a new broadcaster
 *
 * @param address - multicast group address
 * @param srcAddress - address of interface we should use to broadcast.
 * @param port - udp port to use
 * @param ttl - packet ttl
 * @throws IOException
 */
public JdpBroadcaster(InetAddress address, InetAddress srcAddress, int port, int ttl)
        throws IOException, JdpException {
    this.addr = address;
    this.port = port;

    ProtocolFamily family = (address instanceof Inet6Address)
            ? StandardProtocolFamily.INET6 : StandardProtocolFamily.INET;

    channel = DatagramChannel.open(family);
    channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    channel.setOption(StandardSocketOptions.IP_MULTICAST_TTL, ttl);

    // with srcAddress equal to null, this constructor do exactly the same as
    // if srcAddress is not passed
    if (srcAddress != null) {
        // User requests particular interface to bind to
        NetworkInterface interf = NetworkInterface.getByInetAddress(srcAddress);
        try {
            channel.bind(new InetSocketAddress(srcAddress, 0));
        } catch (UnsupportedAddressTypeException ex) {
            throw new JdpException("Unable to bind to source address");
        }
        channel.setOption(StandardSocketOptions.IP_MULTICAST_IF, interf);
    }
}
项目:smart_plan    文件:Utilty.java   
/**
 * 获取手机ip地址,如果WiFi可以,则返回WiFi的ip,否则就返回网络ip.
 *
 * @param context 上下文
 * @return ip
 */
public static String getDeviceNetworkIp(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context
            .CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
    if (networkInfo != null) {
        if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {  //wifi
            WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifi.getConnectionInfo();
            int ip = wifiInfo.getIpAddress();
            return convertToIp(ip);
        } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) { // gprs
            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();
                        //这里4.0以上部分手机返回的地址将会是ipv6地址,而且在4G下也验证了返回的是
                        //ipv6,而服务器不处理ipv6地址
                        if (!inetAddress.isLoopbackAddress() && !(inetAddress
                                instanceof Inet6Address)) {
                            return inetAddress.getHostAddress().toString();
                        }

                    }

                }
            } catch (SocketException e) {
                Log.e(TAG, "e", e);
            }
        }
    }
    return DEFAULT_NETWORK_IP;
}
项目:codedemos    文件:DeviceUtil.java   
/**
 * <p>need permission {@code <uses-permission android:name="android.permission.INTERNET"/>}</p>
 */
private static String getMacAddressByNetworkInterface() {
    try {
        List<NetworkInterface> nis = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface ni : nis) {
            if (!ni.getName().equalsIgnoreCase("wlan0")) continue;
            byte[] macBytes = ni.getHardwareAddress();
            if (macBytes != null && macBytes.length > 0) {
                StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    res1.append(String.format("%02x:", b));
                }
                return res1.deleteCharAt(res1.length() - 1).toString();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "02:00:00:00:00:00";
}
项目:LANClipboard    文件:LAN.java   
public static ArrayList<String> getIPv4s() {
    ArrayList<String> IPs = new ArrayList<String>();

    Enumeration<NetworkInterface> interfaces = null;
    try {
        interfaces = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e1) {
        e1.printStackTrace();
    }

    while(interfaces.hasMoreElements()) {
        NetworkInterface thisinterface = interfaces.nextElement();
        Enumeration<InetAddress> addresses = thisinterface.getInetAddresses();
        while(addresses.hasMoreElements()) {
            String IP = addresses.nextElement().getHostAddress();
            if(Pdot.split(IP).length == 4 && !IP.equals("127.0.0.1")) { // 255.255.255.255 = 4 dots
                IPs.add(IP);
            }
        }
    }

    return IPs;
}
项目:incubator-netbeans    文件:LocalAddressUtils.java   
/**
 * Tries to guess if the network interface is a virtual adapter
 * by one of the makers of virtualization solutions (e.g. VirtualBox,
 * VMware, etc). This is by no means a bullet proof method which is
 * why it errs on the side of caution.
 * 
 * @param nif network interface
 * @return 
 */
public static boolean isSoftwareVirtualAdapter(NetworkInterface nif) {

    try {
        // VirtualBox uses a semi-random MAC address for their adapter
        // where the first 3 bytes are always the same:
        //    Windows, Mac OS X, Linux : begins with 0A-00-27
        //    Solaris:  begins with 10-00-27
        // (above from VirtualBox source code)
        //
        byte[] macAddress = nif.getHardwareAddress();
        if (macAddress != null & macAddress.length >= 3) {
            if ((macAddress[0] == 0x0A || macAddress[0] == 0x08) &&
                    (macAddress[1] == 0x00) &&
                    (macAddress[2] == 0x27)) {                
                return true;
            }
        }
        return false;
    } catch (SocketException ex) {
        return false;
    }
}
项目:launcher-backend    文件:MissionControlImpl.java   
private String getUserId(Projectile projectile) {
    final Identity identity = projectile.getOpenShiftIdentity();
    String userId;
    // User ID will be the token
    if (identity instanceof TokenIdentity) {
        userId = ((TokenIdentity) identity).getToken();
    } else {
        // For users authenticating with user/password (ie. local/Minishift/CDK)
        // let's identify them by their MAC address (which in a VM is the MAC address
        // of the VM, or a fake one, but all we can really rely on to uniquely identify
        // an installation
        final StringBuilder sb = new StringBuilder();
        try {
            byte[] macAddress = NetworkInterface.getByInetAddress(InetAddress.getLocalHost()).getHardwareAddress();
            sb.append(LOCAL_USER_ID_PREFIX);
            for (int i = 0; i < macAddress.length; i++) {
                sb.append(String.format("%02X%s", macAddress[i], (i < macAddress.length - 1) ? "-" : ""));
            }
            userId = sb.toString();
        } catch (Exception e) {
            userId = LOCAL_USER_ID_PREFIX + "UNKNOWN";
        }
    }
    return userId;
}
项目:Elasticsearch    文件:NetworkUtils.java   
/** Returns all global scope addresses for interfaces that are up. */
static InetAddress[] getGlobalAddresses() throws SocketException {
    List<InetAddress> list = new ArrayList<>();
    for (NetworkInterface intf : getInterfaces()) {
        if (intf.isUp()) {
            for (InetAddress address : Collections.list(intf.getInetAddresses())) {
                if (address.isLoopbackAddress() == false && 
                    address.isSiteLocalAddress() == false &&
                    address.isLinkLocalAddress() == false) {
                    list.add(address);
                }
            }
        }
    }
    if (list.isEmpty()) {
        throw new IllegalArgumentException("No up-and-running global-scope (public) addresses found, got " + getInterfaces());
    }
    return list.toArray(new InetAddress[list.size()]);
}
项目:Auto.js    文件:Device.java   
private static String getMacByInterface() throws SocketException {
    List<NetworkInterface> networkInterfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
    for (NetworkInterface networkInterface : networkInterfaces) {
        if (networkInterface.getName().equalsIgnoreCase("wlan0")) {
            byte[] macBytes = networkInterface.getHardwareAddress();
            if (macBytes == null) {
                return null;
            }

            StringBuilder mac = new StringBuilder();
            for (byte b : macBytes) {
                mac.append(String.format("%02X:", b));
            }

            if (mac.length() > 0) {
                mac.deleteCharAt(mac.length() - 1);
            }
            return mac.toString();
        }
    }
    return null;
}
项目:athena    文件:OspfConfigUtil.java   
/**
 * Returns interface IP by index.
 *
 * @param interfaceIndex interface index
 * @return interface IP by index
 */
private static Ip4Address getInterfaceIp(int interfaceIndex) {
    Ip4Address ipAddress = null;
    try {
        NetworkInterface networkInterface = NetworkInterface.getByIndex(interfaceIndex);
        Enumeration ipAddresses = networkInterface.getInetAddresses();
        while (ipAddresses.hasMoreElements()) {
            InetAddress address = (InetAddress) ipAddresses.nextElement();
            if (!address.isLinkLocalAddress()) {
                ipAddress = Ip4Address.valueOf(address.getAddress());
                break;
            }
        }
    } catch (Exception e) {
        log.debug("Error while getting Interface IP by index");
        return OspfUtil.DEFAULTIP;
    }
    return ipAddress;
}
项目:RepWifiApp    文件:Engine.java   
@Override
public boolean isInterfaceAvailable(String ifaceName) throws SocketException {

    /*
     * String[]ifaces = getAvailableInterfaces(); if(ifaces == null ||
     * ifaces.length == 0){ return false; }
     * 
     * for(String name : ifaces){
     * 
     * if (name.equals(ifaceName)){ return true; } }
     * 
     * return false;
     */

    Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
    while (interfaces.hasMoreElements()) {
        NetworkInterface nif = interfaces.nextElement();
        String nm = nif.getName();
        if (nm.equals(ifaceName)) {
            return true;
        }
    }
    return false;

}
项目: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 "";
}
项目:WifiChatSharing    文件:MessageActivity.java   
private String getIpAddress() {
    String ip = "";
    try {
        Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (enumNetworkInterfaces.hasMoreElements()) {

            NetworkInterface networkInterface = enumNetworkInterfaces.nextElement();
            Enumeration<InetAddress> enumInetAddress = networkInterface.getInetAddresses();

            while (enumInetAddress.hasMoreElements()) {
                InetAddress inetAddress = enumInetAddress.nextElement();

                if (inetAddress.isSiteLocalAddress()) {
                    ip += inetAddress.getHostAddress();
                }
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
        ip += "Something Wrong! " + e.toString() + "\n";
    }
    return ip;
}
项目:hadoop-oss    文件:DNS.java   
/**
 * @return NetworkInterface for the given subinterface name (eg eth0:0)
 *    or null if no interface with the given name can be found  
 */
private static NetworkInterface getSubinterface(String strInterface)
    throws SocketException {
  Enumeration<NetworkInterface> nifs = 
    NetworkInterface.getNetworkInterfaces();

  while (nifs.hasMoreElements()) {
    Enumeration<NetworkInterface> subNifs = 
      nifs.nextElement().getSubInterfaces();

    while (subNifs.hasMoreElements()) {
      NetworkInterface nif = subNifs.nextElement();
      if (nif.getName().equals(strInterface)) {
        return nif;
      }
    }
  }
  return null;
}
项目:rmq4note    文件:MixAll.java   
public static List<String> getLocalInetAddress() {
    List<String> inetAddressList = new ArrayList<String>();
    try {
        Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
        while (enumeration.hasMoreElements()) {
            NetworkInterface networkInterface = enumeration.nextElement();
            Enumeration<InetAddress> addrs = networkInterface.getInetAddresses();
            while (addrs.hasMoreElements()) {
                inetAddressList.add(addrs.nextElement().getHostAddress());
            }
        }
    } catch (SocketException e) {
        throw new RuntimeException("get local inet address fail", e);
    }

    return inetAddressList;
}
项目:jdk8u-jdk    文件:ProbeIB.java   
public static void main(String[] args) throws IOException {
    Scanner s = new Scanner(new File(args[0]));
    try {
        while (s.hasNextLine()) {
            String link = s.nextLine();
            NetworkInterface ni = NetworkInterface.getByName(link);
            if (ni != null) {
                Enumeration<InetAddress> addrs = ni.getInetAddresses();
                while (addrs.hasMoreElements()) {
                    InetAddress addr = addrs.nextElement();
                    System.out.println(addr.getHostAddress());
                }
            }
        }
    } finally {
        s.close();
    }
}
项目:fdt    文件:LocalHost.java   
static public String getPublicIP4() {

        Enumeration<NetworkInterface> ifs;
        try {
            ifs = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            e.printStackTrace();
            return null;
        }

        while (ifs.hasMoreElements()) {
            NetworkInterface iface = ifs.nextElement();
            Enumeration<InetAddress> iad = iface.getInetAddresses();
            while (iad.hasMoreElements()) {
                InetAddress localIP = iad.nextElement();
                if (!localIP.isSiteLocalAddress() && !localIP.isLoopbackAddress()) {
                    // found an IPv4 address
                    if (localIP instanceof java.net.Inet4Address)
                        return localIP.getHostAddress();
                }
            }
        }
        return null;
    }
项目:maxcube-java    文件:MinaDiscoveryClientTest.java   
@Test
public void testGoodCaseDiscovery() throws Exception {
    int port = randomIntBetween(60000, 65000);
    String data = randomAsciiOfLength(18);
    try (MinaDiscoveryClient client = new MinaDiscoveryClient(port)) {
        List<DiscoveredCube> cubes = new ArrayList<>();
        NetworkInterface localhostInterface = NetworkInterface.getByInetAddress(InetAddress.getLocalHost());
        client.startServer(localhostInterface, cubes);

        try (DatagramSocket clientSocket = new DatagramSocket()) {
            clientSocket.setReuseAddress(true);
            byte[] discoverBytes = data.getBytes(UTF_8);
            DatagramPacket sendPacket = new DatagramPacket(discoverBytes, discoverBytes.length, InetAddress.getLocalHost(), port);
            logger.info("Sending UDP packet to [{}:{}]", InetAddress.getLocalHost(), port);
            clientSocket.send(sendPacket);
        }

        // waiting without sleeping would be better
        Thread.sleep(500);

        assertThat(cubes, hasSize(greaterThan(0)));
        assertThat(cubes.stream().filter(cube -> cube.id.equals(data.substring(8, 18))).count(), is(1L));
    }
}
项目:hadoop-oss    文件:TestNetUtils.java   
/** 
 * Test for {@link NetUtils#isLocalAddress(java.net.InetAddress)}
 */
@Test
public void testIsLocalAddress() throws Exception {
  // Test - local host is local address
  assertTrue(NetUtils.isLocalAddress(InetAddress.getLocalHost()));

  // Test - all addresses bound network interface is local address
  Enumeration<NetworkInterface> interfaces = NetworkInterface
      .getNetworkInterfaces();
  if (interfaces != null) { // Iterate through all network interfaces
    while (interfaces.hasMoreElements()) {
      NetworkInterface i = interfaces.nextElement();
      Enumeration<InetAddress> addrs = i.getInetAddresses();
      if (addrs == null) {
        continue;
      }
      // Iterate through all the addresses of a network interface
      while (addrs.hasMoreElements()) {
        InetAddress addr = addrs.nextElement();
        assertTrue(NetUtils.isLocalAddress(addr));
      }
    }
  }
  assertFalse(NetUtils.isLocalAddress(InetAddress.getByName("8.8.8.8")));
}
项目:hadoop-oss    文件:MiniRPCBenchmark.java   
private void configureSuperUserIPAddresses(Configuration conf,
    String superUserShortName) throws IOException {
  ArrayList<String> ipList = new ArrayList<String>();
  Enumeration<NetworkInterface> netInterfaceList = NetworkInterface
      .getNetworkInterfaces();
  while (netInterfaceList.hasMoreElements()) {
    NetworkInterface inf = netInterfaceList.nextElement();
    Enumeration<InetAddress> addrList = inf.getInetAddresses();
    while (addrList.hasMoreElements()) {
      InetAddress addr = addrList.nextElement();
      ipList.add(addr.getHostAddress());
    }
  }
  StringBuilder builder = new StringBuilder();
  for (String ip : ipList) {
    builder.append(ip);
    builder.append(',');
  }
  builder.append("127.0.1.1,");
  builder.append(InetAddress.getLocalHost().getCanonicalHostName());
  conf.setStrings(DefaultImpersonationProvider.getTestProvider().
          getProxySuperuserIpConfKey(superUserShortName), builder.toString());
}
项目:AndroidBasicLibs    文件:DeviceUtils.java   
public static String getGPRSIP() {
    String ip = null;
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
            for (Enumeration<InetAddress> enumIpAddr = en.nextElement().getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    ip = inetAddress.getHostAddress();
                }
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
        ip = null;
    }
    return ip;
}
项目:ADBToolKitsInstaller    文件:MainActivity.java   
public 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 (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress() && inetAddress.isSiteLocalAddress()) {
                    return inetAddress.getHostAddress();
                }
            }
        }
    } catch (SocketException ex) {
        ex.printStackTrace();
    }
    return "0.0.0.0";
}
项目:Simpler    文件:NetWorkUtils.java   
/**
 * 获取本机IP地址
 *
 * @return null:没有网络连接
 */
public static String getIpAddress() {
    try {
        NetworkInterface nerworkInterface;
        InetAddress inetAddress;
        for (Enumeration<NetworkInterface> en
             = NetworkInterface.getNetworkInterfaces();
             en.hasMoreElements(); ) {
            nerworkInterface = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr
                 = nerworkInterface.getInetAddresses();
                 enumIpAddr.hasMoreElements(); ) {
                inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
        return null;
    } catch (SocketException ex) {
        ex.printStackTrace();
        return null;
    }
}
项目:ViewDebugHelper    文件:NetworkUtil.java   
/** 获得IP信息 */
public static String getOneIPV4() {
    ArrayList<String> list = new ArrayList<String>();
    String result = "ip get failed";
    try {
        for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = (NetworkInterface) en.nextElement();
            for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();
                if (inetAddress instanceof Inet4Address) {
                    if (!inetAddress.isLoopbackAddress()) {
                        list.add(inetAddress.getHostAddress());
                    }
                }
            }
        }
    } catch (SocketException ex) {
    }
    if (list.size() > 0)
        result = list.get(0);
    return result;
}
项目:jdk8u-jdk    文件:Inet6AddressSerializationTest.java   
static void testAllNetworkInterfaces() throws Exception {
    System.err.println("\n testAllNetworkInterfaces: \n ");
    for (Enumeration<NetworkInterface> e = NetworkInterface
            .getNetworkInterfaces(); e.hasMoreElements();) {
        NetworkInterface netIF = e.nextElement();
        for (Enumeration<InetAddress> iadrs = netIF.getInetAddresses(); iadrs
                .hasMoreElements();) {
            InetAddress iadr = iadrs.nextElement();
            if (iadr instanceof Inet6Address) {
                System.err.println("Test NetworkInterface:  " + netIF);
                Inet6Address i6adr = (Inet6Address) iadr;
                System.err.println("Testing with " + iadr);
                System.err.println(" scoped iface: "
                        + i6adr.getScopedInterface());
                testInet6AddressSerialization(i6adr, 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;
}
项目:Elasticsearch    文件:IfConfig.java   
/** format network interface flags */
private static String formatFlags(NetworkInterface nic) throws SocketException {
    StringBuilder flags = new StringBuilder();
    if (nic.isUp()) {
        flags.append("UP ");
    }
    if (nic.supportsMulticast()) {
        flags.append("MULTICAST ");
    }
    if (nic.isLoopback()) {
        flags.append("LOOPBACK ");
    }
    if (nic.isPointToPoint()) {
        flags.append("POINTOPOINT ");
    }
    if (nic.isVirtual()) {
        flags.append("VIRTUAL ");
    }
    flags.append("mtu:" + nic.getMTU());
    flags.append(" index:" + nic.getIndex());
    return flags.toString();
}
项目:letv    文件:NetworkUtils.java   
public static Map<String, String> getAllMac(String delimiter) {
    try {
        Map<String, String> macMap = new HashMap();
        Enumeration<?> e = NetworkInterface.getNetworkInterfaces();
        while (e.hasMoreElements()) {
            NetworkInterface item = (NetworkInterface) e.nextElement();
            byte[] mac = item.getHardwareAddress();
            if (mac != null && mac.length > 0) {
                if (ETH_MAC.equalsIgnoreCase(item.getName()) || WALN_MAC.equalsIgnoreCase(item.getName())) {
                    macMap.put(item.getName(), bytesToHexWithDelimiter(mac, delimiter));
                }
            }
        }
        return macMap;
    } catch (Throwable e2) {
        LogTool.e(TAG, "", e2);
        return null;
    }
}
项目:elasticsearch_my    文件:NetworkUtils.java   
/** Returns all site-local scope (private) addresses for interfaces that are up. */
static InetAddress[] getSiteLocalAddresses() throws SocketException {
    List<InetAddress> list = new ArrayList<>();
    for (NetworkInterface intf : getInterfaces()) {
        if (intf.isUp()) {
            for (InetAddress address : Collections.list(intf.getInetAddresses())) {
                if (address.isSiteLocalAddress()) {
                    list.add(address);
                }
            }
        }
    }
    if (list.isEmpty()) {
        throw new IllegalArgumentException("No up-and-running site-local (private) addresses found, got " + getInterfaces());
    }
    return list.toArray(new InetAddress[list.size()]);
}
项目:openjdk-jdk10    文件:NetworkConfigurationProbe.java   
public static void main(String... args) throws Exception {
    NetworkConfiguration.printSystemConfiguration(out);

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

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

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

    list = nc.ip6Addresses()
              .map(Inet6Address::toString)
              .collect(joining(" "));
    out.println("ip6Addresses: " +  list);
}
项目:BloomReader    文件:NewBookListenerService.java   
private String getOurIpAddress() {
    String ip = "";
    try {
        Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (enumNetworkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = enumNetworkInterfaces.nextElement();
            Enumeration<InetAddress> enumInetAddress = networkInterface.getInetAddresses();
            while (enumInetAddress.hasMoreElements()) {
                InetAddress inetAddress = enumInetAddress.nextElement();

                if (inetAddress.isSiteLocalAddress()) {
                    return inetAddress.getHostAddress();
                }

            }

        }

    } catch (SocketException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        ip += "Something Wrong! " + e.toString() + "\n";
    }

    return ip;
}
项目:athena    文件:Controller.java   
/**
 * Returns interface IP by index.
 *
 * @param interfaceIndex interface index
 * @return interface IP by index
 */
private Ip4Address getInterfaceIp(int interfaceIndex) {
    Ip4Address ipAddress = null;
    try {
        NetworkInterface networkInterface = NetworkInterface.getByIndex(interfaceIndex);
        Enumeration ipAddresses = networkInterface.getInetAddresses();
        while (ipAddresses.hasMoreElements()) {
            InetAddress address = (InetAddress) ipAddresses.nextElement();
            if (!address.isLinkLocalAddress()) {
                ipAddress = Ip4Address.valueOf(address.getAddress());
                break;
            }
        }
    } catch (Exception e) {
        log.debug("Error while getting Interface IP by index");
        return OspfUtil.DEFAULTIP;
    }

    return ipAddress;
}
项目:TabShop-KitchenDisplay    文件:DisplayActivity.java   
public String[] getLocalIpAddress() {          
    ArrayList<String> addresses = new ArrayList<String>();
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            if(!intf.isPointToPoint() && intf.isUp()) {
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && (inetAddress instanceof Inet4Address)) {
                        addresses.add(inetAddress.getHostAddress());
                    }
                }
            }
         }
     } catch (SocketException ex) {
         CrashLog.getInstance().logException(ex);
     }
     return addresses.toArray(new String[0]);
}
项目:Android-Bridge-App    文件:Utils.java   
/**
 * Returns MAC address of the given interface name.
 *
 * @param interfaceName eth0, wlan0 or NULL=use first interface
 * @return mac address or empty string
 */
public static String getMACAddress(String interfaceName) {
    try {
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface intf : interfaces) {
            if (interfaceName != null) {
                if (!intf.getName().equalsIgnoreCase(interfaceName)) continue;
            }
            byte[] mac = intf.getHardwareAddress();
            if (mac == null) return "";
            StringBuilder buf = new StringBuilder();
            for (int idx = 0; idx < mac.length; idx++)
                buf.append(String.format("%02X:", mac[idx]));
            if (buf.length() > 0) buf.deleteCharAt(buf.length() - 1);
            return buf.toString();
        }
    } catch (Exception ex) {
    } // for now eat exceptions
    return "";
    /*try {
        // this is so Linux hack
        return loadFileAsString("/sys/class/net/" +interfaceName + "/address").toUpperCase().trim();
    } catch (IOException ex) {
        return null;
    }*/
}
项目:remote-storage-android-things    文件:FTPManager.java   
private String getLocalIpAddress() {
    String ipAddrrss = "";
    try {
        Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (enumNetworkInterfaces.hasMoreElements()) {
            Enumeration<InetAddress> enumInetAddress = enumNetworkInterfaces.nextElement().getInetAddresses();
            while (enumInetAddress.hasMoreElements()) {
                InetAddress inetAddress = enumInetAddress.nextElement();
                if (inetAddress.isSiteLocalAddress()) {
                    ipAddrrss = ipAddrrss + inetAddress.getHostAddress();
                }
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }
    return ipAddrrss;
}
项目:ja-micro    文件:RegistrationManager.java   
private void updateIpAddress() {
    try {
        Enumeration<NetworkInterface> b = NetworkInterface.getNetworkInterfaces();
        ipAddress = null;
        while( b.hasMoreElements()){
            NetworkInterface iface = b.nextElement();
            if (iface.getName().startsWith("dock")) {
                continue;
            }
            for ( InterfaceAddress f : iface.getInterfaceAddresses()) {
                if (f.getAddress().isSiteLocalAddress()) {
                    ipAddress = f.getAddress().getHostAddress();
                }
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }
}
项目: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);
    }
}
项目:Reer    文件:InetAddresses.java   
private void useMulticastFallback() throws SocketException {
    logger.debug("No multicast interfaces, using fallbacks");
    Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
    while (networkInterfaces.hasMoreElements()) {
        multicastInterfaces.add(networkInterfaces.nextElement());
    }
}
项目:openjdk-jdk10    文件:NetworkConfiguration.java   
/** Prints all the system interface information to the give stream. */
public static void printSystemConfiguration(PrintStream out) {
    try {
        out.println("*** all system network interface configuration ***");
        for (NetworkInterface nif : list(getNetworkInterfaces())) {
            out.print(interfaceInformation(nif));
        }
        out.println("*** end ***");
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
项目:yaacc-code    文件:YaaccContentDirectory.java   
/**
 * get the ip address of the device
 * 
 * @return the address or null if anything went wrong
 * 
 */
public String getIpAddress() {
    String hostAddress = null;
    try {
        for (Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
                .getNetworkInterfaces(); networkInterfaces
                .hasMoreElements();) {
            NetworkInterface networkInterface = networkInterfaces
                    .nextElement();
            for (Enumeration<InetAddress> inetAddresses = networkInterface
                    .getInetAddresses(); inetAddresses.hasMoreElements();) {
                InetAddress inetAddress = inetAddresses.nextElement();
                if (!inetAddress.isLoopbackAddress()
                        && InetAddressUtils.isIPv4Address(inetAddress
                                .getHostAddress())) {

                    hostAddress = inetAddress.getHostAddress();
                }

            }
        }
    } catch (SocketException se) {
        Log.d(YaaccUpnpServerService.class.getName(),
                "Error while retrieving network interfaces", se);
    }
    // maybe wifi is off we have to use the loopback device
    hostAddress = hostAddress == null ? "0.0.0.0" : hostAddress;
    return hostAddress;
}
项目:GitHub    文件:NetworkUtils.java   
/**
 * 获取IP地址
 * <p>需添加权限 {@code <uses-permission android:name="android.permission.INTERNET"/>}</p>
 *
 * @param useIPv4 是否用IPv4
 * @return IP地址
 */
public static String getIPAddress(final boolean useIPv4) {
    try {
        for (Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces(); nis.hasMoreElements(); ) {
            NetworkInterface ni = nis.nextElement();
            // 防止小米手机返回10.0.2.15
            if (!ni.isUp()) continue;
            for (Enumeration<InetAddress> addresses = ni.getInetAddresses(); addresses.hasMoreElements(); ) {
                InetAddress inetAddress = addresses.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    String hostAddress = inetAddress.getHostAddress();
                    boolean isIPv4 = hostAddress.indexOf(':') < 0;
                    if (useIPv4) {
                        if (isIPv4) return hostAddress;
                    } else {
                        if (!isIPv4) {
                            int index = hostAddress.indexOf('%');
                            return index < 0 ? hostAddress.toUpperCase() : hostAddress.substring(0, index).toUpperCase();
                        }
                    }
                }
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }
    return null;
}