Networkinterface java

Networkinterface java DEFAULT

Java Code Examples for java.net.NetworkInterface#getNetworkInterfaces()

The following examples show how to use java.net.NetworkInterface#getNetworkInterfaces() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.

Example 1

private static 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()); LOG.info("Local Ip addresses: " + builder.toString()); conf.setStrings(DefaultImpersonationProvider.getTestProvider(). getProxySuperuserIpConfKey(superUserShortName), builder.toString()); }

Example 2

public static void main(String[] args) throws Exception { Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces(); while (nics.hasMoreElements()) { NetworkInterface nic = nics.nextElement(); for (InterfaceAddress iaddr : nic.getInterfaceAddresses()) { boolean valid = checkPrefix(iaddr); if (!valid) { passed = false; debug(nic.getName(), iaddr); } InetAddress ia = iaddr.getAddress(); if (ia.isLoopbackAddress() && ia instanceof Inet4Address) { // assumption: prefix length will always be 8 if (iaddr.getNetworkPrefixLength() != 8) { out.println("Expected prefix of 8, got " + iaddr); passed = false; } } } } if (!passed) throw new RuntimeException("Failed: some interfaces have invalid prefix lengths"); }

Example 3

public static InetAddress getWiFiIpAddress() { try { for (Enumeration<NetworkInterface> enNetI = NetworkInterface .getNetworkInterfaces(); enNetI.hasMoreElements(); ) { NetworkInterface netI = enNetI.nextElement(); if (netI.getDisplayName().equals("wlan0") || netI.getDisplayName().equals("eth0")) { for (Enumeration<InetAddress> enumIpAddr = netI .getInetAddresses(); enumIpAddr.hasMoreElements(); ) { InetAddress inetAddress = enumIpAddr.nextElement(); if (inetAddress instanceof Inet4Address && !inetAddress.isLoopbackAddress()) { return inetAddress; } } } } } catch (SocketException e) { e.printStackTrace(); } return null; }

Example 4

private String getAddress() { try { Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces(); while (netInterfaces.hasMoreElements()) { NetworkInterface ni = netInterfaces.nextElement(); Enumeration<InetAddress> ips = ni.getInetAddresses(); while (ips.hasMoreElements()) { InetAddress ip = ips.nextElement(); if (ip.getHostAddress().equals("127.0.0.1")) { continue; } if (!ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) { return ip.getHostAddress(); } } } } catch (Exception e) { log.error("get ip failed", e); } return null; }

Example 5

/** * Returns a list of all the addresses on the system. * @param inclLoopback * if {@code true}, include the loopback addresses * @param ipv4Only * it {@code true}, only IPv4 addresses will be included */ static List<InetAddress> getAddresses(boolean inclLoopback, boolean ipv4Only) throws SocketException { ArrayList<InetAddress> list = new ArrayList<InetAddress>(); Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces(); for (NetworkInterface netInf : Collections.list(nets)) { Enumeration<InetAddress> addrs = netInf.getInetAddresses(); for (InetAddress addr : Collections.list(addrs)) { if (!list.contains(addr) && (inclLoopback ? true : !addr.isLoopbackAddress()) && (ipv4Only ? (addr instanceof Inet4Address) : true)) { list.add(addr); } } } return list; }

Example 6

/** * 获得外网IP * * @return 外网IP */ public static String getInternetIp() { try { Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces(); InetAddress ip = null; Enumeration<InetAddress> addrs; while (networks.hasMoreElements()) { addrs = networks.nextElement().getInetAddresses(); while (addrs.hasMoreElements()) { ip = addrs.nextElement(); if (ip != null && ip instanceof Inet4Address && ip.isSiteLocalAddress() && !ip.getHostAddress().equals(INTRANET_IP)) { return ip.getHostAddress(); } } } // 如果没有外网IP,就返回内网IP return INTRANET_IP; } catch (Exception e) { throw new RuntimeException(e); } }

Example 7

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); } } } }

Example 8

/** * Retrieve the first validated local ip address(the Public and LAN ip addresses are validated). * * @return the local address * @throws SocketException the socket exception */ public static InetAddress getLocalInetAddress() throws SocketException { // enumerates all network interfaces Enumeration<NetworkInterface> enu = NetworkInterface.getNetworkInterfaces(); while (enu.hasMoreElements()) { NetworkInterface ni = enu.nextElement(); if (ni.isLoopback()) { continue; } Enumeration<InetAddress> addressEnumeration = ni.getInetAddresses(); while (addressEnumeration.hasMoreElements()) { InetAddress address = addressEnumeration.nextElement(); // ignores all invalidated addresses if (address.isLinkLocalAddress() || address.isLoopbackAddress() || address.isAnyLocalAddress()) { continue; } return address; } } throw new RuntimeException("No validated local address!"); }

Example 9

/** * Check if at least one network interface is up and active (i.e. has an address) * * @return true if network available */ static boolean checkNetwork() { boolean up = false; Enumeration<NetworkInterface> enumeration; try { enumeration = NetworkInterface.getNetworkInterfaces(); if (enumeration != null) { while (!up && enumeration.hasMoreElements()) { NetworkInterface networkInterface = enumeration.nextElement(); up = networkInterface.isUp() && !networkInterface.isLoopback() && networkInterface.getInetAddresses().hasMoreElements(); } } } catch (NoSuchMethodError error) { ExchangeSession.LOGGER.debug("Unable to test network interfaces (not available under Java 1.5)"); up = true; } catch (SocketException exc) { ExchangeSession.LOGGER.error("DavMail configuration exception: \n Error listing network interfaces " + exc.getMessage(), exc); } return up; }

Example 10

/** * Returns all local IP addresses (IPv4 and IPv6). * * @throws RuntimeException if resolution fails */ public static List<String> resolveLocalIPs(boolean ipv4Only) { ArrayList<String> addresses = new ArrayList<>(); try { Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces(); while (nics.hasMoreElements()) { NetworkInterface nic = nics.nextElement(); Enumeration<InetAddress> inetAddresses = nic.getInetAddresses(); while (inetAddresses.hasMoreElements()) { InetAddress address = inetAddresses.nextElement(); if (address instanceof Inet6Address) { if (!ipv4Only) { addresses.add(toIpV6AddressName((Inet6Address) address)); } } else { addresses.add(address.getHostAddress()); } } } } catch (SocketException e) { throw new RuntimeException("Cannot resolve local network addresses", e); } return Collections.unmodifiableList(addresses); }

Example 11

/** * 获取本机IP(2G/3G/4G) */ public static String getLocalIpBy3G() { 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) { // if (!inetAddress.isLoopbackAddress() && inetAddress // instanceof Inet6Address) { return inetAddress.getHostAddress().toString(); } } } } catch (Exception e) { e.printStackTrace(); } return null; }

Example 12

@Test public void testConflictRegionServerHostnameConfigurationsAbortServer() throws Exception { Enumeration<NetworkInterface> netInterfaceList = NetworkInterface.getNetworkInterfaces(); while (netInterfaceList.hasMoreElements()) { NetworkInterface ni = netInterfaceList.nextElement(); Enumeration<InetAddress> addrList = ni.getInetAddresses(); // iterate through host addresses and use each as hostname while (addrList.hasMoreElements()) { InetAddress addr = addrList.nextElement(); if (addr.isLoopbackAddress() || addr.isLinkLocalAddress() || addr.isMulticastAddress()) { continue; } String hostName = addr.getHostName(); LOG.info("Found " + hostName + " on " + ni); TEST_UTIL.getConfiguration().set(DNS.MASTER_HOSTNAME_KEY, hostName); // "hbase.regionserver.hostname" and "hbase.regionserver.hostname.disable.master.reversedns" // are mutually exclusive. Exception should be thrown if both are used. TEST_UTIL.getConfiguration().set(DNS.RS_HOSTNAME_KEY, hostName); TEST_UTIL.getConfiguration().setBoolean(HRegionServer.RS_HOSTNAME_DISABLE_MASTER_REVERSEDNS_KEY, true); try { StartMiniClusterOption option = StartMiniClusterOption.builder() .numMasters(NUM_MASTERS).numRegionServers(NUM_RS).numDataNodes(NUM_RS).build(); TEST_UTIL.startMiniCluster(option); } catch (Exception e) { Throwable t1 = e.getCause(); Throwable t2 = t1.getCause(); assertTrue(t1.getMessage()+" - "+t2.getMessage(), t2.getMessage().contains( HRegionServer.RS_HOSTNAME_DISABLE_MASTER_REVERSEDNS_KEY + " and " + DNS.RS_HOSTNAME_KEY + " are mutually exclusive")); return; } finally { TEST_UTIL.shutdownMiniCluster(); } assertTrue("Failed to validate against conflict hostname configurations", false); } } }

Example 13

public static String getIPAddress(Context context) { Context appContext = context.getApplicationContext(); ConnectivityManager connectivityManager = (ConnectivityManager) appContext.getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivityManager == null) { return ""; } @SuppressLint("MissingPermission") NetworkInfo info = connectivityManager.getActiveNetworkInfo(); if (info != null && info.isConnected()) { if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//当前使用2G/3G/4G网络 try { //Enumeration<NetworkInterface> en=NetworkInterface.getNetworkInterfaces(); 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) { return inetAddress.getHostAddress(); } } } } catch (SocketException e) { e.printStackTrace(); } } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络 WifiManager wifiManager = (WifiManager) appContext.getSystemService(Context.WIFI_SERVICE); if (wifiManager == null) { return ""; } @SuppressLint("MissingPermission") WifiInfo wifiInfo = wifiManager.getConnectionInfo(); String ipAddress = intIp2StrIp(wifiInfo.getIpAddress());//得到IPV4地址 return ipAddress; } } else { //当前无网络连接,请在设置中打开网络 } return ""; }

Example 14

/*** * 获取mac地址 * @return */ public static String getMacAddress() { String address = null; // 把当前机器上的访问网络接口的存入 Enumeration集合中 try { Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface netWork = interfaces.nextElement(); // 如果存在硬件地址并可以使用给定的当前权限访问,则返回该硬件地址(通常是 MAC)。 byte[] by = netWork.getHardwareAddress(); if (by == null || by.length == 0) { continue; } StringBuilder builder = new StringBuilder(); for (byte b : by) { builder.append(String.format("%02X:", b)); } if (builder.length() > 0) { builder.deleteCharAt(builder.length() - 1); } String mac = builder.toString(); // 从路由器上在线设备的MAC地址列表,可以印证设备Wifi的 name 是 wlan0 if (netWork.getName().equals("wlan0")) { address = mac; } } } catch (Exception e) { e.printStackTrace(); } return address; }

Example 15

public static String getMacAddress() throws SocketException { Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); while (networkInterfaces.hasMoreElements()) { NetworkInterface networkInterface = networkInterfaces.nextElement(); if (!networkInterface.getName().equalsIgnoreCase("wlan0")) continue; byte[] addresses = networkInterface.getHardwareAddress(); if (addresses == null || addresses.length == 0) return ""; StringBuilder builder = new StringBuilder(); for (byte b : addresses) { builder.append(String.format(Locale.getDefault(), "%02x:", b)); } return builder.deleteCharAt(builder.length() - 1).toString(); } return ""; }

Example 16

public static Set<String> getNetworkInterfaces(){ Set<String> ipAndHosts = new HashSet<>(); try { // Get the system hostname and add it. String hostName = getHostName(); ipAndHosts.add(hostName); Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces(); while (nics.hasMoreElements()) { NetworkInterface nic = nics.nextElement(); ipAndHosts.add(nic.getDisplayName()); Enumeration<InetAddress> inets = nic.getInetAddresses(); while (inets.hasMoreElements()) { InetAddress inet = inets.nextElement(); ipAndHosts.add(inet.getHostAddress()); ipAndHosts.add(inet.getHostName()); ipAndHosts.add(inet.getCanonicalHostName()); } } } catch (Exception e) { logger.error(Constants.CONSOLE, "Error occurred acquiring IP's and hostnames", e); } return ipAndHosts; }

Example 17

public static String getLocalhostByNetworkInterface() throws SocketException { List<String> candidatesHost = new ArrayList<String>(); Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces(); while (enumeration.hasMoreElements()) { NetworkInterface networkInterface = enumeration.nextElement(); // Workaround for docker0 bridge if ("docker0".equals(networkInterface.getName()) || !networkInterface.isUp()) { continue; } Enumeration<InetAddress> addrs = networkInterface.getInetAddresses(); while (addrs.hasMoreElements()) { InetAddress address = addrs.nextElement(); if (address.isLoopbackAddress()) { continue; } //ip4 higher priority if (address instanceof Inet6Address) { candidatesHost.add(address.getHostAddress()); continue; } return address.getHostAddress(); } } if (!candidatesHost.isEmpty()) { return candidatesHost.get(0); } return null; }

Example 18

/** * Get IP address for localhost. * * @return IP address for localhost */ public static String getIp() { if (null != cachedIpAddress) { return cachedIpAddress; } Enumeration<NetworkInterface> netInterfaces; try { netInterfaces = NetworkInterface.getNetworkInterfaces(); } catch (final SocketException ex) { throw new HostException(ex); } String localIpAddress = null; while (netInterfaces.hasMoreElements()) { NetworkInterface netInterface = netInterfaces.nextElement(); Enumeration<InetAddress> ipAddresses = netInterface.getInetAddresses(); while (ipAddresses.hasMoreElements()) { InetAddress ipAddress = ipAddresses.nextElement(); if (isPublicIpAddress(ipAddress)) { String publicIpAddress = ipAddress.getHostAddress(); cachedIpAddress = publicIpAddress; return publicIpAddress; } if (isLocalIpAddress(ipAddress)) { localIpAddress = ipAddress.getHostAddress(); } } } cachedIpAddress = localIpAddress; return localIpAddress; }

Example 19

void setInterfaceNames() { final String addressesRangeUSB = "192.168.42."; final String addressesRangeWiFi = "192.168.43."; usbTetherOn = false; ethernetOn = false; try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) { NetworkInterface intf = en.nextElement(); if (intf.isLoopback()) { continue; } if (intf.isVirtual()) { continue; } if (!intf.isUp()) { continue; } setVpnInterfaceName(intf); if (intf.isPointToPoint()) { continue; } if (intf.getHardwareAddress() == null) { continue; } if (intf.getName().replaceAll("\\d+", "").equalsIgnoreCase("eth")) { ethernetOn = true; ethernetInterfaceName = intf.getName(); Log.i(LOG_TAG, "LAN interface name " + ethernetInterfaceName); } for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) { InetAddress inetAddress = enumIpAddr.nextElement(); String hostAddress = inetAddress.getHostAddress(); if (hostAddress.contains(addressesRangeWiFi)) { this.apIsOn = true; wifiAPInterfaceName = intf.getName(); Log.i(LOG_TAG, "WiFi AP interface name " + wifiAPInterfaceName); } if (hostAddress.contains(addressesRangeUSB)) { usbTetherOn = true; usbModemInterfaceName = intf.getName(); Log.i(LOG_TAG, "USB Modem interface name " + usbModemInterfaceName); } } } } catch (SocketException e) { Log.e(LOG_TAG, "Tethering SocketException " + e.getMessage() + " " + e.getCause()); } if (usbTetherOn && !new PrefManager(context).getBoolPref("ModemIsON")) { new PrefManager(context).setBoolPref("ModemIsON", true); ModulesStatus.getInstance().setIptablesRulesUpdateRequested(context, true); } else if (!usbTetherOn && new PrefManager(context).getBoolPref("ModemIsON")) { new PrefManager(context).setBoolPref("ModemIsON", false); ModulesStatus.getInstance().setIptablesRulesUpdateRequested(context, true); } }

Example 20

private static long initialSeed() { String pp = java.security.AccessController.doPrivileged( new sun.security.action.GetPropertyAction( "java.util.secureRandomSeed")); if (pp != null && pp.equalsIgnoreCase("true")) { byte[] seedBytes = java.security.SecureRandom.getSeed(8); long s = (long)(seedBytes[0]) & 0xffL; for (int i = 1; i < 8; ++i) s = (s << 8) | ((long)(seedBytes[i]) & 0xffL); return s; } long h = 0L; try { Enumeration<NetworkInterface> ifcs = NetworkInterface.getNetworkInterfaces(); boolean retry = false; // retry once if getHardwareAddress is null while (ifcs.hasMoreElements()) { NetworkInterface ifc = ifcs.nextElement(); if (!ifc.isVirtual()) { // skip fake addresses byte[] bs = ifc.getHardwareAddress(); if (bs != null) { int n = bs.length; int m = Math.min(n >>> 1, 4); for (int i = 0; i < m; ++i) h = (h << 16) ^ (bs[i] << 8) ^ bs[n-1-i]; if (m < 4) h = (h << 8) ^ bs[n-1-m]; h = mix64(h); break; } else if (!retry) retry = true; else break; } } } catch (Exception ignore) { } return (h ^ mix64(System.currentTimeMillis()) ^ mix64(System.nanoTime())); }
Sours: https://www.programcreek.com/java-api-examples/?class=java.net.NetworkInterface&method=getNetworkInterfaces

Java.net.NetworkInterface class in Java

This class represents network interface, both software as well as hardware, its name, list of IP addresses assigned to it and all related information. It can be used in cases when we want to specifically use a particular interface for transmitting our packet on a system with multiple NICs. 
What is a Network Interface? 
A network interface can be thought of as a point at which your computer connects to the network. It is not necessarily a piece of hardware but can also be implemented in a software. For example a loopback interface which is used for testing purposes. 
Methods : 
 

1.getName() : Returns the name of this network interface. 
 

Syntax : public String getName()

2.getInetAddresses() : Returns an enumeration of all Inetaddresses bound to this network interface, if security manager allows it. 
 

Syntax :public Enumeration getInetAddresses()

3.getInterfaceAddresses() : Returns a list of all interface addresses on this interface. 
 

Syntax :public List getInterfaceAddresses()

4.getSubInterfaces() : Returns an enumeration of all the sub or virtual interfaces of this network interface. For example, eth0:2 is a sub interface of eth0. 
 



Syntax :public Enumeration getSubInterfaces()

5.getParent() : In case of a sub interface, this method returns the parent interface. If this is not a subinterface, this method will return null. 
 

Syntax :public NetworkInterface getParent()

6.getIndex() : Returns the index assigned to this network interface by the system. Indexes can be used in place of long names to refer to any interface on the device. 
 

Syntax :public int getIndex()

7.getDisplayName() : This method returns the name of network interface in a readable string format. 
 

Syntax :public String getDisplayName()

8.getByName() : Finds and returns the network interface with the specified name, or null if none exists. 
 

Syntax :public static NetworkInterface getByName(String name) throws SocketException Parameters : name : name of network interface to search for. Throws : SocketException : if I/O error occurs.

9.getByIndex() : Performs similar function as the previous function with index used as search parameter instead of name. 
 

Syntax :public static NetworkInterface getByIndex(int index) throws SocketException Parameters : index : index of network interface to search for. Throws : SocketException : if I/O error occurs.

10.getByInetAddress() : This method is widely used as it returns the network interface the specified inetaddress is bound to. If an InetAddress is bound to multiple interfaces, any one of the interfaces may be returned. 
 

Syntax : public static NetworkInterface getByInetAddress(InetAddress addr) throws SocketException Parameters : addr : address to search for Throws : SocketException : If IO error occurs

11.getNetworkInterfaces() : Returns all the network interfaces on the system. 
 

Syntax :public static Enumeration getNetworkInterfaces() throws SocketException Throws : SocketException : If IO error occurs

12.isUp() : Returns a boolean value indicating if this network interface is up and running. 
 



Syntax : public boolean isUp()

13.isLoopback() : Returns a boolean value indicating if this interface is a loopback interface or not. 
 

Syntax : public boolean isLoopback()

14.isPointToPoint() : Returns a boolean value indicating if this interface is a point to point interface or not. 
 

Syntax : public boolean isPointToPoint()

15.supportsMulticast() : Returns a boolean value indicating if this interface supports multicasting or not. 
 

Syntax : public boolean supportsMulticast()

16.getHardwareAddress() : Returns a byte array containing the hardware address(MAC) address of this interface. The caller must have appropriate permissions before calling this method. 
 

public byte[] getHardwareAddress()

17.getMTU() : Returns the maximum transmission unit of this interface. An MTU is the largest size of the packet or frame that can be sent in packet based network. 
 

Syntax :public int getMTU()

18.isVirtual() : Returns a boolean value indicating whether this interface is a virtual interface or not. Virtual interfaces are used in conjunction physical interfaces to provide additional values such as addresses and MTU. 
 

Syntax : public boolean isVirtual()

19.equals() : THis method is used to compare two network interfaces for equality. Two network interfaces are equal if they have same name and addresses bound to them. 
 

Syntax :public boolean equals(Object obj) Parameters : obj : Object to compare this network interface for equality

20.hashCode() : Returns the hashcode value for this object. 
 

Syntax :public int hashCode()

21.toString() : Returns a textual description of this object. 
 

Syntax :public String toString()

Java Implementation : 
 

Java

Output : 
 

Information about present Network Interfaces... Interface Name: lo Interface display name: Software Loopback Interface 1 Hardware Address: null Parent: null Index: 1 Interface addresses: /127.0.0.1 /0:0:0:0:0:0:0:1 InetAddresses associated with this interface: /127.0.0.1 /0:0:0:0:0:0:0:1 MTU: -1 Subinterfaces: [] is loopback: true is virtual: false is point to point: false Supports Multicast: true Interface Name: wlan5 Interface display name: Dell Wireless 1705 802.11b|g|n (2.4GHZ) Hardware Address: [100, 90, 4, -90, 2, 15] Parent: null Index: 16 Interface addresses: /192.168.43.96 /2405:205:1486:9a1b:e567:b46f:198a:fe0c /2405:205:1486:9a1b:8c93:9f82:6dd2:350c /fe80:0:0:0:e567:b46f:198a:fe0c%wlan5 InetAddresses associated with this interface: /192.168.43.96 /2405:205:1486:9a1b:e567:b46f:198a:fe0c /2405:205:1486:9a1b:8c93:9f82:6dd2:350c /fe80:0:0:0:e567:b46f:198a:fe0c%wlan5 MTU: 1500 Subinterfaces: [] is loopback: false is virtual: false is point to point: false Supports Multicast: true Network interface 1: name:lo (Software Loopback Interface 1) loclhost associated with: name:lo (Software Loopback Interface 1) nif==nif2: false HashCode : 2544

The output of the above program will differ if you run it on your system as than it will display information about your network interfaces.
References : 
Official Java Documentation 
This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected] See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notesarrow_drop_up
Sours: https://www.geeksforgeeks.org/java-net-networkinterface-class-java/
  1. Ctp cat parts
  2. Carole johnson nj
  3. Aaliyah gravesite

This documentation differs from the official API.Jadeite adds extra features to the API including: variable font sizes, constructions examples, placeholders for classes and methods, and auto-generated “See Also” links. Additionally it is missing some items found in standard Javadoc documentation, including: generics type information, “Deprecated” tags and comments, “See Also” links, along with other minor differences. Please send any questions or feedback to [email protected]



java.net
class NetworkInterface


Most common way to construct:

Based on 51 examples


public final class NetworkInterface extends Object

This class represents a Network Interface made up of a name, and a list of IP addresses assigned to this interface. It is used to identify the local interface on which a multicast group is joined. Interfaces are normally known by names such as "le0".

See Also (auto-generated):

Method Summary

          Compares this object against the specified object.

          Convenience method to search for a network interface that has the specified Internet Protocol (IP) address bound to it.

          Searches for the network interface with the specified name.

          Get the display name of this network interface.

          Returns the hardware address (usually MAC) of the interface if it has one and if it can be accessed given the current privileges.

          Convenience method to return an Enumeration with all or a subset of the InetAddresses bound to this network interface.

          Get a List of all or a subset of the of this network interface.

          Returns the Maximum Transmission Unit (MTU) of this interface.

          Get the name of this network interface.

          Returns all the interfaces on this machine.

          Returns the parent NetworkInterface of this interface if this is a subinterface, or if it is a physical (non virtual) interface or has no parent.

          Get an Enumeration with all the subinterfaces (also known as virtual interfaces) attached to this network interface.

          Returns a hash code value for the object.

          Returns whether a network interface is a loopback interface.

          Returns whether a network interface is a point to point interface.

          Returns whether a network interface is up and running.

          Returns whether this interface is a virtual interface (also called subinterface).

          Returns whether a network interface supports multicasting or not.

          Returns a string representation of the object.
 
Methods inherited from class java.lang.Object
 

equals

public boolean equals(Object obj)
Compares this object against the specified object. The result is if and only if the argument is not and it represents the same NetworkInterface as this object.

Two instances of represent the same NetworkInterface if both name and addrs are the same for both.

Overrides:
in class
Parameters:
- the object to compare against.
Returns:
if the objects are the same; otherwise.

getByInetAddress

public static NetworkInterfacegetByInetAddress(InetAddress addr) throws SocketException
Convenience method to search for a network interface that has the specified Internet Protocol (IP) address bound to it.

If the specified IP address is bound to multiple network interfaces it is not defined which network interface is returned.

Parameters:
- The to search with.
Returns:
A or if there is no network interface with the specified IP address.
Throws:
- If an I/O error occurs.

getByName

public static NetworkInterfacegetByName(String name) throws SocketException
Searches for the network interface with the specified name.
Parameters:
- The name of the network interface.
Returns:
A with the specified name, or if there is no network interface with the specified name.
Throws:
- If an I/O error occurs.

getDisplayName

public StringgetDisplayName()
Get the display name of this network interface. A display name is a human readable String describing the network device.
Returns:
the display name of this network interface, or null if no display name is available.

getHardwareAddress

public byte[] getHardwareAddress() throws SocketException
Returns the hardware address (usually MAC) of the interface if it has one and if it can be accessed given the current privileges.
Returns:
a byte array containing the address or if the address doesn't exist or is not accessible.
Throws:
- if an I/O error occurs.

getInetAddresses

public EnumerationgetInetAddresses()
Convenience method to return an Enumeration with all or a subset of the InetAddresses bound to this network interface.

If there is a security manager, its method is called for each InetAddress. Only InetAddresses where the doesn't throw a SecurityException will be returned in the Enumeration.

Returns:
an Enumeration object with all or a subset of the InetAddresses bound to this network interface

getInterfaceAddresses

public ListgetInterfaceAddresses()
Get a List of all or a subset of the of this network interface.

If there is a security manager, its method is called with the InetAddress for each InterfaceAddress. Only InterfaceAddresses where the doesn't throw a SecurityException will be returned in the List.

Returns:
a object with all or a subset of the InterfaceAddresss of this network interface

getMTU

public int getMTU() throws SocketException
Returns the Maximum Transmission Unit (MTU) of this interface.
Returns:
the value of the MTU for that interface.
Throws:
- if an I/O error occurs.

getName

public StringgetName()
Get the name of this network interface.
Returns:
the name of this network interface

getNetworkInterfaces

public static EnumerationgetNetworkInterfaces() throws SocketException
Returns all the interfaces on this machine. Returns null if no network interfaces could be found on this machine. NOTE: can use getNetworkInterfaces()+getInetAddresses() to obtain all IP addresses for this node
Returns:
an Enumeration of NetworkInterfaces found on this machine
Throws:
- if an I/O error occurs.

getParent

public NetworkInterfacegetParent()
Returns the parent NetworkInterface of this interface if this is a subinterface, or if it is a physical (non virtual) interface or has no parent.
Returns:
The this interface is attached to.

getSubInterfaces

public EnumerationgetSubInterfaces()
Get an Enumeration with all the subinterfaces (also known as virtual interfaces) attached to this network interface.

For instance eth0:1 will be a subinterface to eth0.

Returns:
an Enumeration object with all of the subinterfaces of this network interface

hashCode

public int hashCode()
Overrides:
in class

isLoopback

public boolean isLoopback() throws SocketException
Returns whether a network interface is a loopback interface.
Returns:
if the interface is a loopback interface.
Throws:
- if an I/O error occurs.

isPointToPoint

public boolean isPointToPoint() throws SocketException
Returns whether a network interface is a point to point interface. A typical point to point interface would be a PPP connection through a modem.
Returns:
if the interface is a point to point interface.
Throws:
- if an I/O error occurs.

isUp

public boolean isUp() throws SocketException
Returns whether a network interface is up and running.
Returns:
if the interface is up and running.
Throws:
- if an I/O error occurs.

isVirtual

public boolean isVirtual()
Returns whether this interface is a virtual interface (also called subinterface). Virtual interfaces are, on some systems, interfaces created as a child of a physical interface and given different settings (like address or MTU). Usually the name of the interface will the name of the parent followed by a colon (:) and a number identifying the child since there can be several virtual interfaces attached to a single physical interface.
Returns:
if this interface is a virtual interface.

supportsMulticast

public boolean supportsMulticast() throws SocketException
Returns whether a network interface supports multicasting or not.
Returns:
if the interface supports Multicasting.
Throws:
- if an I/O error occurs.

toString

public StringtoString()
Overrides:
in class


This documentation differs from the official API.Jadeite adds extra features to the API including: variable font sizes, constructions examples, placeholders for classes and methods, and auto-generated “See Also” links. Additionally it is missing some items found in standard Javadoc documentation, including: generics type information, “Deprecated” tags and comments, “See Also” links, along with other minor differences. Please send any questions or feedback to [email protected]

Sours: http://edelstein.pebbles.cs.cmu.edu/jadeite/main.php?api=java6&state=class&package=java.net&class=NetworkInterface
Finding Network Interface names and their addresses in Java
  • Method Detail

    • getName

      public String getName()

      Get the name of this network interface.

      Returns:
      the name of this network interface
    • getInetAddresses

      public Enumeration<InetAddress> getInetAddresses()
      Get an Enumeration with all or a subset of the InetAddresses bound to this network interface.

      If there is a security manager, its method is called for each InetAddress. Only InetAddresses where the doesn't throw a SecurityException will be returned in the Enumeration. However, if the caller has the ("getNetworkInformation") permission, then all InetAddresses are returned.

      Returns:
      an Enumeration object with all or a subset of the InetAddresses bound to this network interface
      See Also:
    • inetAddresses

      public Stream<InetAddress> inetAddresses()
      Get a Stream of all or a subset of the InetAddresses bound to this network interface.

      If there is a security manager, its method is called for each InetAddress. Only InetAddresses where the doesn't throw a SecurityException will be returned in the Stream. However, if the caller has the ("getNetworkInformation") permission, then all InetAddresses are returned.

      Returns:
      a Stream object with all or a subset of the InetAddresses bound to this network interface
      Since:
      9
    • getInterfaceAddresses

      public List<InterfaceAddress> getInterfaceAddresses()
      Get a List of all or a subset of the of this network interface.

      If there is a security manager, its method is called with the InetAddress for each InterfaceAddress. Only InterfaceAddresses where the doesn't throw a SecurityException will be returned in the List.

      Returns:
      a object with all or a subset of the InterfaceAddresss of this network interface
      Since:
      1.6
    • getSubInterfaces

      public Enumeration<NetworkInterface> getSubInterfaces()
      Get an Enumeration with all the subinterfaces (also known as virtual interfaces) attached to this network interface.

      For instance eth0:1 will be a subinterface to eth0.

      Returns:
      an Enumeration object with all of the subinterfaces of this network interface
      Since:
      1.6
      See Also:
    • subInterfaces

      public Stream<NetworkInterface> subInterfaces()

      Get a Stream of all subinterfaces (also known as virtual interfaces) attached to this network interface.

      Returns:
      a Stream object with all of the subinterfaces of this network interface
      Since:
      9
    • getParent

      public NetworkInterface getParent()

      Returns the parent NetworkInterface of this interface if this is a subinterface, or if it is a physical (non virtual) interface or has no parent.

      Returns:
      The this interface is attached to.
      Since:
      1.6
    • getIndex

      public int getIndex()

      Returns the index of this network interface. The index is an integer greater or equal to zero, or for unknown. This is a system specific value and interfaces with the same name can have different indexes on different machines.

      Returns:
      the index of this network interface or if the index is unknown
      Since:
      1.7
      See Also:
    • getDisplayName

      public String getDisplayName()

      Get the display name of this network interface. A display name is a human readable String describing the network device.

      Returns:
      a non-empty string representing the display name of this network interface, or null if no display name is available.
    • getByName

      public static NetworkInterface getByName​(String name) throws SocketException

      Searches for the network interface with the specified name.

      Parameters:
      - The name of the network interface.
      Returns:
      A with the specified name, or if there is no network interface with the specified name.
      Throws:
      - If an I/O error occurs.
      - If the specified name is .
    • getByIndex

      public static NetworkInterface getByIndex​(int index) throws SocketException

      Get a network interface given its index.

      Parameters:
      - an integer, the index of the interface
      Returns:
      the NetworkInterface obtained from its index, or if there is no interface with such an index on the system
      Throws:
      - if an I/O error occurs.
      - if index has a negative value
      Since:
      1.7
      See Also:
    • getByInetAddress

      public static NetworkInterface getByInetAddress​(InetAddress addr) throws SocketException
      Convenience method to search for a network interface that has the specified Internet Protocol (IP) address bound to it.

      If the specified IP address is bound to multiple network interfaces it is not defined which network interface is returned.

      Parameters:
      - The to search with.
      Returns:
      A or if there is no network interface with the specified IP address.
      Throws:
      - If an I/O error occurs.
      - If the specified address is .
    • getNetworkInterfaces

      public static Enumeration<NetworkInterface> getNetworkInterfaces() throws SocketException

      Returns an of all the interfaces on this machine. The contains at least one element, possibly representing a loopback interface that only supports communication between entities on this machine.

      API Note:
      this method can be used in combination with to obtain all IP addresses for this node
      Returns:
      an Enumeration of NetworkInterfaces found on this machine
      Throws:
      - if an I/O error occurs, or if the platform does not have at least one configured network interface.
      See Also:
    • networkInterfaces

      public static Stream<NetworkInterface> networkInterfaces() throws SocketException

      Returns a of all the interfaces on this machine. The contains at least one interface, possibly representing a loopback interface that only supports communication between entities on this machine.

      API Note:
      this method can be used in combination with } to obtain a stream of all IP addresses for this node, for example:
      Returns:
      a Stream of NetworkInterfaces found on this machine
      Throws:
      - if an I/O error occurs, or if the platform does not have at least one configured network interface.
      Since:
      9
    • isUp

      public boolean isUp() throws SocketException

      Returns whether a network interface is up and running.

      Returns:
      if the interface is up and running.
      Throws:
      - if an I/O error occurs.
      Since:
      1.6
    • isLoopback

      public boolean isLoopback() throws SocketException

      Returns whether a network interface is a loopback interface.

      Returns:
      if the interface is a loopback interface.
      Throws:
      - if an I/O error occurs.
      Since:
      1.6
    • isPointToPoint

      public boolean isPointToPoint() throws SocketException

      Returns whether a network interface is a point to point interface. A typical point to point interface would be a PPP connection through a modem.

      Returns:
      if the interface is a point to point interface.
      Throws:
      - if an I/O error occurs.
      Since:
      1.6
    • supportsMulticast

      public boolean supportsMulticast() throws SocketException

      Returns whether a network interface supports multicasting or not.

      Returns:
      if the interface supports Multicasting.
      Throws:
      - if an I/O error occurs.
      Since:
      1.6
    • getHardwareAddress

      public byte[] getHardwareAddress() throws SocketException

      Returns the hardware address (usually MAC) of the interface if it has one and if it can be accessed given the current privileges. If a security manager is set, then the caller must have the permission ("getNetworkInformation").

      Returns:
      a byte array containing the address, or if the address doesn't exist, is not accessible or a security manager is set and the caller does not have the permission NetPermission("getNetworkInformation")
      Throws:
      - if an I/O error occurs.
      Since:
      1.6
    • getMTU

      public int getMTU() throws SocketException

      Returns the Maximum Transmission Unit (MTU) of this interface.

      Returns:
      the value of the MTU for that interface.
      Throws:
      - if an I/O error occurs.
      Since:
      1.6
    • isVirtual

      public boolean isVirtual()

      Returns whether this interface is a virtual interface (also called subinterface). Virtual interfaces are, on some systems, interfaces created as a child of a physical interface and given different settings (like address or MTU). Usually the name of the interface will the name of the parent followed by a colon (:) and a number identifying the child since there can be several virtual interfaces attached to a single physical interface.

      Returns:
      if this interface is a virtual interface.
      Since:
      1.6
    • equals

      public boolean equals​(Object obj)
      Compares this object against the specified object. The result is if and only if the argument is not and it represents the same NetworkInterface as this object.

      Two instances of represent the same NetworkInterface if both name and addrs are the same for both.

      Overrides:
       in class 
      Parameters:
      - the object to compare against.
      Returns:
      if the objects are the same; otherwise.
      See Also:
Sours: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/net/NetworkInterface.html

Java networkinterface

Best Java code snippets using java.net.NetworkInterface.getNetworkInterfaces(Showing top 20 results out of 8,082)

Refine searchRefine arrow

  • Common ways to obtain NetworkInterface

    private void myMethod () {

    NetworkInterfacen=
    • Codota IconEnumeration interfaces;interfaces.nextElement()
    • Codota IconEnumeration en;(NetworkInterface) en.nextElement()
    • Codota IconString interfaceName;NetworkInterface.getByName(interfaceName)
    • Smart code suggestions by Tabnine

    }

    publicstatic InetAddress getLocalIPAddress() { try { Enumeration<?> netInterfaces = NetworkInterface.getNetworkInterfaces(); InetAddress inetAddress = null; while (netInterfaces.hasMoreElements()) { NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement(); Enumeration<?> e2 = ni.getInetAddresses(); while (e2.hasMoreElements()) { inetAddress = (InetAddress) e2.nextElement(); if (!inetAddress.isLoopbackAddress() && !inetAddress.getHostAddress().contains(":")) { return inetAddress; } } } } catch (Exception e) { LOG.error("getLocalIP error", e); } return null; } }
    publicstatic List<NetworkInterface> getAllAvailableInterfaces() throws SocketException { List<NetworkInterface> retval=new ArrayList<>(10); NetworkInterface intf; for(Enumeration en=NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) { intf=(NetworkInterface)en.nextElement(); retval.add(intf); } return retval; }
    @Override public Optional<InetAddress> getLocalInetAddress(Predicate<InetAddress> predicate) { try { return Collections.list(NetworkInterface.getNetworkInterfaces()).stream() .flatMap(ni -> Collections.list(ni.getInetAddresses()).stream()) .filter(a -> a.getHostAddress() != null) .filter(predicate) .findFirst(); } catch (SocketException e) { thrownew IllegalStateException("Can not retrieve network interfaces", e); } } }
    publicstatic String getIPAddress(boolean useIPv4) { try { List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface intf : interfaces) { List<InetAddress> addrs = Collections.list(intf.getInetAddresses()); for (InetAddress addr : addrs) { if (!addr.isLoopbackAddress()) { String sAddr = addr.getHostAddress(); boolean isIPv4 = sAddr.indexOf(':')<0; if (useIPv4) { if (isIPv4) return sAddr; } else { if (!isIPv4) { int delim = sAddr.indexOf('%'); return delim<0 ? sAddr.toUpperCase() : sAddr.substring(0, delim).toUpperCase(); } } } } } } catch (Exception ex) { } return""; }
    List<NetworkInterface> itfs = new ArrayList<>(); for (NetworkInterface itf : asIterable(NetworkInterface.getNetworkInterfaces())) itfs.add(itf); boolean found = false; for (InetAddress addr : asIterable(itf.getInetAddresses())) { if (!addr.isLoopbackAddress() && !addr.isLinkLocalAddress() && reachable(itf, addr, reachTimeout)) { locHost = addr;
    List<InetAddress> addrList = new ArrayList<InetAddress>(); for(NetworkInterface ifc : NetworkInterface.getNetworkInterfaces()) { if(ifc.isUp()) { for(InetAddress addr : ifc.getInetAddresses()) { addrList.add(addr); } } }
    publicstatic NetworkInterface findInterfaceWithScopeId(String scopeName) { final Enumeration<NetworkInterface> enumeration; try { enumeration = NetworkInterface.getNetworkInterfaces(); } catch (SocketException ignored) { return null; } while (enumeration.hasMoreElements()) { final NetworkInterface net = enumeration.nextElement(); if (net.getName().equals(scopeName)) { return net; } } return null; }
    List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface intf : interfaces) { if (interfaceName != null) { List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface intf : interfaces) { List<InetAddress> addrs = Collections.list(intf.getInetAddresses()); for (InetAddress addr : addrs) { if (!addr.isLoopbackAddress()) { String sAddr = addr.getHostAddress();
    publicstaticvoid main(String[] args) throws UnknownHostException, SocketException { System.out.println("Current IP address : " + InetAddress.getLocalHost().getHostAddress()); for(NetworkInterface network : IterableEnumeration.make(NetworkInterface.getNetworkInterfaces())) { byte[] mac = network.getHardwareAddress(); if(mac != null) { System.out.print("Current MAC address : "); StringBuilder sb = new StringBuilder(); for (int i = 0; i < mac.length; i++) { sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "")); } System.out.println(sb.toString()); for(InetAddress address : IterableEnumeration.make(network.getInetAddresses())) { System.out.println("\tBound to:"+address.getHostAddress()); } } } }
    Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); List<NetworkInterface> nis = interfaces == null ? Collections.<NetworkInterface>emptyList() : Collections.list(interfaces); List<InetAddress> addresses = new ArrayList<InetAddress>(); for (NetworkInterface ni : nis) { if (ni.isUp() && !ni.isLoopback()) { addresses.addAll(Collections.list(ni.getInetAddresses()));
    publicstatic 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) { thrownew RuntimeException("get local inet address fail", e); } return inetAddressList; }
    privatestatic List<NetworkInterface> getAllNetworkInterfaces() { Enumeration<NetworkInterface> networkInterfaces; try { networkInterfaces = NetworkInterface.getNetworkInterfaces(); if (networkInterfaces == null) { return Collections.emptyList(); } List<NetworkInterface> ifaces = new ArrayList<>(); while (networkInterfaces.hasMoreElements()) { ifaces.add(networkInterfaces.nextElement()); } return ifaces; } catch (SocketException e) { return Collections.emptyList(); } }
    publicstaticsynchronized Collection<String> allLocalIps() { List<String> ips = new ArrayList<>(4); try { Enumeration<NetworkInterface> itfs = NetworkInterface.getNetworkInterfaces(); if (itfs != null) { for (NetworkInterface itf : asIterable(itfs)) { if (!itf.isLoopback()) { Enumeration<InetAddress> addrs = itf.getInetAddresses(); for (InetAddress addr : asIterable(addrs)) { String hostAddr = addr.getHostAddress(); if (!addr.isLoopbackAddress() && !ips.contains(hostAddr)) ips.add(hostAddr); } } } } } catch (SocketException ignore) { return Collections.emptyList(); } Collections.sort(ips); return ips; }
    private Socks5Proxy() { this.serverProcess = new Socks5ServerProcess(); Enumeration<NetworkInterface> networkInterfaces; try { networkInterfaces = NetworkInterface.getNetworkInterfaces(); } catch (SocketException e) { thrownew IllegalStateException(e); } Set<String> localHostAddresses = new HashSet<>(); for (NetworkInterface networkInterface : Collections.list(networkInterfaces)) { Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses(); for (InetAddress address : Collections.list(inetAddresses)) { localHostAddresses.add(address.getHostAddress()); } } if (localHostAddresses.isEmpty()) { thrownew IllegalStateException("Could not determine any local host address"); } replaceLocalAddresses(localHostAddresses); }
    privatestatic String getMacAddress() throws IOException { final Enumeration<NetworkInterface> net = NetworkInterface.getNetworkInterfaces(); final StringBuilder result = new StringBuilder(); while (net.hasMoreElements()) { final NetworkInterface element = net.nextElement(); byte[] mac = element.getHardwareAddress(); if (mac != null) { for (byte b : mac) { result.append(String.format("%02x", b)); } } } return result.toString(); }
    privatestatic IPInfo getIPInfo() { try { List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface intf : interfaces) { List<InetAddress> addrs = Collections.list(intf.getInetAddresses()); for (InetAddress addr : addrs) { if (!addr.isLoopbackAddress()) { String sAddr = addr.getHostAddress().toUpperCase(); boolean isIPv4 = isIPv4Address(sAddr); if (isIPv4) { IPInfo info = new IPInfo(); info.addr = addr; info.intf = intf; info.ip = sAddr; info.ip_hex = InetAddress_to_hex(addr); info.netmask_hex = netmask_to_hex(intf.getInterfaceAddresses().get(0).getNetworkPrefixLength()); return info; } } } } } catch (SocketException e) { e.printStackTrace(); } return null; }
    public List<String> call() throws IOException { List<String> names = new ArrayList<String>(); Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces(); while (nis.hasMoreElements()) { NetworkInterface ni = nis.nextElement(); LOGGER.log(Level.FINE, "Listing up IP addresses for {0}", ni.getDisplayName()); Enumeration<InetAddress> e = ni.getInetAddresses(); while (e.hasMoreElements()) { InetAddress ia = e.nextElement(); if(ia.isLoopbackAddress()) { LOGGER.log(Level.FINE, "{0} is a loopback address", ia); continue; } if(!(ia instanceof Inet4Address)) { LOGGER.log(Level.FINE, "{0} is not an IPv4 address", ia); continue; } LOGGER.log(Level.FINE, "{0} is a viable candidate", ia); names.add(ia.getHostAddress()); } } return names; } privatestaticfinallong serialVersionUID = 1L;
    Sours: https://www.tabnine.com/code/java/methods/java.net.NetworkInterface/getNetworkInterfaces
    Finding Network Interface names and their addresses in Java
    Modifier and TypeMethod and Description

    Compares this object against the specified object.

    Get a network interface given its index.

    Convenience method to search for a network interface that has the specified Internet Protocol (IP) address bound to it.

    Searches for the network interface with the specified name.

    Get the display name of this network interface.

    Returns the hardware address (usually MAC) of the interface if it has one and if it can be accessed given the current privileges.

    Returns the index of this network interface.

    Convenience method to return an Enumeration with all or a subset of the InetAddresses bound to this network interface.

    Get a List of all or a subset of the of this network interface.

    Returns the Maximum Transmission Unit (MTU) of this interface.

    Get the name of this network interface.

    Returns all the interfaces on this machine.

    Returns the parent NetworkInterface of this interface if this is a subinterface, or if it is a physical (non virtual) interface or has no parent.

    Get an Enumeration with all the subinterfaces (also known as virtual interfaces) attached to this network interface.

    Returns a hash code value for the object.

    Returns whether a network interface is a loopback interface.

    Returns whether a network interface is a point to point interface.

    Returns whether a network interface is up and running.

    Returns whether this interface is a virtual interface (also called subinterface).

    Returns whether a network interface supports multicasting or not.

    Returns a string representation of the object.

    Sours: https://docs.oracle.com/javase/7/docs/api/java/net/NetworkInterface.html

    Similar news:

    /* * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions.*/packagejava.net;importjava.util.Enumeration;importjava.util.NoSuchElementException;importsun.security.action.*;importjava.security.AccessController;/** * This class represents a Network Interface made up of a name, * and a list of IP addresses assigned to this interface. * It is used to identify the local interface on which a multicast group * is joined. * * Interfaces are normally known by names such as "le0". * * @since 1.4*/publicfinalclassNetworkInterface {privateString name;privateString displayName;privateint index;privateInetAddress addrs[];privateInterfaceAddress bindings[];privateNetworkInterface childs[];privateNetworkInterface parent =null;privateboolean virtual =false;privatestaticfinalNetworkInterface defaultInterface;privatestaticfinalint defaultIndex; /* index of defaultInterface */static {AccessController.doPrivileged(newjava.security.PrivilegedAction<Void>() {publicVoidrun() {System.loadLibrary("net");returnnull; } }); init(); defaultInterface =DefaultInterface.getDefault();if (defaultInterface !=null) { defaultIndex = defaultInterface.getIndex(); } else { defaultIndex =0; } }/** * Returns an NetworkInterface object with index set to 0 and name to null. * Setting such an interface on a MulticastSocket will cause the * kernel to choose one interface for sending multicast packets. **/NetworkInterface() { }NetworkInterface(Stringname, intindex, InetAddress[] addrs) {this.name = name;this.index = index;this.addrs = addrs; }/** * Get the name of this network interface. * * @return the name of this network interface*/publicStringgetName() {return name; }/** * Convenience method to return an Enumeration with all or a * subset of the InetAddresses bound to this network interface. * <p> * If there is a security manager, its {@code checkConnect} * method is called for each InetAddress. Only InetAddresses where * the {@code checkConnect} doesn't throw a SecurityException * will be returned in the Enumeration. However, if the caller has the * {@link NetPermission}("getNetworkInformation") permission, then all * InetAddresses are returned. * @return an Enumeration object with all or a subset of the InetAddresses * bound to this network interface*/publicEnumeration<InetAddress>getInetAddresses() {classcheckedAddressesimplementsEnumeration<InetAddress> {privateint i=0, count=0;privateInetAddress local_addrs[];checkedAddresses() { local_addrs =newInetAddress[addrs.length];boolean trusted =true;SecurityManager sec =System.getSecurityManager();if (sec !=null) {try { sec.checkPermission(newNetPermission("getNetworkInformation")); } catch (SecurityException e) { trusted =false; } }for (int j=0; j<addrs.length; j++) {try {if (sec !=null&&!trusted) { sec.checkConnect(addrs[j].getHostAddress(), -1); } local_addrs[count++] = addrs[j]; } catch (SecurityException e) { } } }publicInetAddressnextElement() {if (i < count) {return local_addrs[i++]; } else {thrownewNoSuchElementException(); } }publicbooleanhasMoreElements() {return (i < count); } }returnnew checkedAddresses(); }/** * Get a List of all or a subset of the {@code InterfaceAddresses} * of this network interface. * <p> * If there is a security manager, its {@code checkConnect} * method is called with the InetAddress for each InterfaceAddress. * Only InterfaceAddresses where the {@code checkConnect} doesn't throw * a SecurityException will be returned in the List. * * @return a {@code List} object with all or a subset of the * InterfaceAddresss of this network interface * @since 1.6*/publicjava.util.List<InterfaceAddress>getInterfaceAddresses() {java.util.List<InterfaceAddress> lst =newjava.util.ArrayList<InterfaceAddress>(1);SecurityManager sec =System.getSecurityManager();for (int j=0; j<bindings.length; j++) {try {if (sec !=null) { sec.checkConnect(bindings[j].getAddress().getHostAddress(), -1); } lst.add(bindings[j]); } catch (SecurityException e) { } }return lst; }/** * Get an Enumeration with all the subinterfaces (also known as virtual * interfaces) attached to this network interface. * <p> * For instance eth0:1 will be a subinterface to eth0. * * @return an Enumeration object with all of the subinterfaces * of this network interface * @since 1.6*/publicEnumeration<NetworkInterface>getSubInterfaces() {classsubIFsimplementsEnumeration<NetworkInterface> {privateint i=0;subIFs() { }publicNetworkInterfacenextElement() {if (i < childs.length) {return childs[i++]; } else {thrownewNoSuchElementException(); } }publicbooleanhasMoreElements() {return (i < childs.length); } }returnnew subIFs(); }/** * Returns the parent NetworkInterface of this interface if this is * a subinterface, or {@code null} if it is a physical * (non virtual) interface or has no parent. * * @return The {@code NetworkInterface} this interface is attached to. * @since 1.6*/publicNetworkInterfacegetParent() {return parent; }/** * Returns the index of this network interface. The index is an integer greater * or equal to zero, or {@code -1} for unknown. This is a system specific value * and interfaces with the same name can have different indexes on different * machines. * * @return the index of this network interface or {@code -1} if the index is * unknown * @see #getByIndex(int) * @since 1.7*/publicintgetIndex() {return index; }/** * Get the display name of this network interface. * A display name is a human readable String describing the network * device. * * @return a non-empty string representing the display name of this network * interface, or null if no display name is available.*/publicStringgetDisplayName() {/* strict TCK conformance */return"".equals(displayName) ?null: displayName; }/** * Searches for the network interface with the specified name. * * @param name * The name of the network interface. * * @return A {@code NetworkInterface} with the specified name, * or {@code null} if there is no network interface * with the specified name. * * @throws SocketException * If an I/O error occurs. * * @throws NullPointerException * If the specified name is {@code null}.*/publicstaticNetworkInterfacegetByName(Stringname) throwsSocketException {if (name ==null)thrownewNullPointerException();return getByName0(name); }/** * Get a network interface given its index. * * @param index an integer, the index of the interface * @return the NetworkInterface obtained from its index, or {@code null} if * there is no interface with such an index on the system * @throws SocketException if an I/O error occurs. * @throws IllegalArgumentException if index has a negative value * @see #getIndex() * @since 1.7*/publicstaticNetworkInterfacegetByIndex(intindex) throwsSocketException {if (index <0)thrownewIllegalArgumentException("Interface index can't be negative");return getByIndex0(index); }/** * Convenience method to search for a network interface that * has the specified Internet Protocol (IP) address bound to * it. * <p> * If the specified IP address is bound to multiple network * interfaces it is not defined which network interface is * returned. * * @param addr * The {@code InetAddress} to search with. * * @return A {@code NetworkInterface} * or {@code null} if there is no network interface * with the specified IP address. * * @throws SocketException * If an I/O error occurs. * * @throws NullPointerException * If the specified address is {@code null}.*/publicstaticNetworkInterfacegetByInetAddress(InetAddressaddr) throwsSocketException {if (addr ==null) {thrownewNullPointerException(); }if (!(addr instanceofInet4Address|| addr instanceofInet6Address)) {thrownewIllegalArgumentException ("invalid address type"); }return getByInetAddress0(addr); }/** * Returns all the interfaces on this machine. The {@code Enumeration} * contains at least one element, possibly representing a loopback * interface that only supports communication between entities on * this machine. * * NOTE: can use getNetworkInterfaces()+getInetAddresses() * to obtain all IP addresses for this node * * @return an Enumeration of NetworkInterfaces found on this machine * @exception SocketException if an I/O error occurs.*/publicstaticEnumeration<NetworkInterface>getNetworkInterfaces()throwsSocketException {finalNetworkInterface[] netifs = getAll();// specified to return null if no network interfacesif (netifs ==null)returnnull;returnnewEnumeration<NetworkInterface>() {privateint i =0;publicNetworkInterfacenextElement() {if (netifs !=null&& i < netifs.length) {NetworkInterface netif = netifs[i++];return netif; } else {thrownewNoSuchElementException(); } }publicbooleanhasMoreElements() {return (netifs !=null&& i < netifs.length); } }; }privatenativestaticNetworkInterface[] getAll()throwsSocketException;privatenativestaticNetworkInterfacegetByName0(Stringname)throwsSocketException;privatenativestaticNetworkInterfacegetByIndex0(intindex)throwsSocketException;privatenativestaticNetworkInterfacegetByInetAddress0(InetAddressaddr)throwsSocketException;/** * Returns whether a network interface is up and running. * * @return {@code true} if the interface is up and running. * @exception SocketException if an I/O error occurs. * @since 1.6*/publicbooleanisUp() throwsSocketException {return isUp0(name, index); }/** * Returns whether a network interface is a loopback interface. * * @return {@code true} if the interface is a loopback interface. * @exception SocketException if an I/O error occurs. * @since 1.6*/publicbooleanisLoopback() throwsSocketException {return isLoopback0(name, index); }/** * Returns whether a network interface is a point to point interface. * A typical point to point interface would be a PPP connection through * a modem. * * @return {@code true} if the interface is a point to point * interface. * @exception SocketException if an I/O error occurs. * @since 1.6*/publicbooleanisPointToPoint() throwsSocketException {return isP2P0(name, index); }/** * Returns whether a network interface supports multicasting or not. * * @return {@code true} if the interface supports Multicasting. * @exception SocketException if an I/O error occurs. * @since 1.6*/publicbooleansupportsMulticast() throwsSocketException {return supportsMulticast0(name, index); }/** * Returns the hardware address (usually MAC) of the interface if it * has one and if it can be accessed given the current privileges. * If a security manager is set, then the caller must have * the permission {@link NetPermission}("getNetworkInformation"). * * @return a byte array containing the address, or {@code null} if * the address doesn't exist, is not accessible or a security * manager is set and the caller does not have the permission * NetPermission("getNetworkInformation") * * @exception SocketException if an I/O error occurs. * @since 1.6*/publicbyte[] getHardwareAddress() throwsSocketException {SecurityManager sec =System.getSecurityManager();if (sec !=null) {try { sec.checkPermission(newNetPermission("getNetworkInformation")); } catch (SecurityException e) {if (!getInetAddresses().hasMoreElements()) {// don't have connect permission to any local addressreturnnull; } } }for (InetAddress addr : addrs) {if (addr instanceofInet4Address) {return getMacAddr0(((Inet4Address)addr).getAddress(), name, index); } }return getMacAddr0(null, name, index); }/** * Returns the Maximum Transmission Unit (MTU) of this interface. * * @return the value of the MTU for that interface. * @exception SocketException if an I/O error occurs. * @since 1.6*/publicintgetMTU() throwsSocketException {return getMTU0(name, index); }/** * Returns whether this interface is a virtual interface (also called
    Sours: https://github.com/frohoff/jdk8u-jdk/blob/master/src/share/classes/java/net/NetworkInterface.java


    1432 1433 1434 1435 1436