/** * 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); } }
/** * 获取手机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; }
/** * <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"; }
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; }
/** * 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; } }
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; }
/** 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()]); }
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; }
/** * 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; }
@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; }
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 ""; }
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; }
/** * @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; }
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; }
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(); } }
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; }
@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)); } }
/** * 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"))); }
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()); }
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; }
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"; }
/** * 获取本机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; } }
/** 获得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; }
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); } } } }
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; }
/** 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(); }
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; } }
/** 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()]); }
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); }
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; }
/** * 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; }
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]); }
/** * 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; }*/ }
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; }
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(); } }
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); } }
private void useMulticastFallback() throws SocketException { logger.debug("No multicast interfaces, using fallbacks"); Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); while (networkInterfaces.hasMoreElements()) { multicastInterfaces.add(networkInterfaces.nextElement()); } }
/** 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); } }
/** * 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; }
/** * 获取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; }