Path: blob/master/src/java.base/share/classes/java/net/NetworkInterface.java
41152 views
/*1* Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package java.net;2627import java.util.Arrays;28import java.util.Enumeration;29import java.util.NoSuchElementException;30import java.util.Spliterator;31import java.util.Spliterators;32import java.util.stream.Stream;33import java.util.stream.StreamSupport;3435/**36* This class represents a Network Interface made up of a name,37* and a list of IP addresses assigned to this interface.38* It is used to identify the local interface on which a multicast group39* is joined.40*41* Interfaces are normally known by names such as "le0".42*43* @since 1.444*/45public final class NetworkInterface {46private String name;47private String displayName;48private int index;49private InetAddress addrs[];50private InterfaceAddress bindings[];51private NetworkInterface childs[];52private NetworkInterface parent = null;53private boolean virtual = false;54private static final NetworkInterface defaultInterface;55private static final int defaultIndex; /* index of defaultInterface */5657static {58jdk.internal.loader.BootLoader.loadLibrary("net");5960init();61defaultInterface = DefaultInterface.getDefault();62if (defaultInterface != null) {63defaultIndex = defaultInterface.getIndex();64} else {65defaultIndex = 0;66}67}6869/**70* Returns an NetworkInterface object with index set to 0 and name to null.71* Setting such an interface on a MulticastSocket will cause the72* kernel to choose one interface for sending multicast packets.73*74*/75NetworkInterface() {76}7778NetworkInterface(String name, int index, InetAddress[] addrs) {79this.name = name;80this.index = index;81this.addrs = addrs;82}8384/**85* Get the name of this network interface.86*87* @return the name of this network interface88*/89public String getName() {90return name;91}9293/**94* Get an Enumeration with all or a subset of the InetAddresses bound to95* this network interface.96* <p>97* If there is a security manager, its {@code checkConnect}98* method is called for each InetAddress. Only InetAddresses where99* the {@code checkConnect} doesn't throw a SecurityException100* will be returned in the Enumeration. However, if the caller has the101* {@link NetPermission}("getNetworkInformation") permission, then all102* InetAddresses are returned.103*104* @return an Enumeration object with all or a subset of the InetAddresses105* bound to this network interface106* @see #inetAddresses()107*/108public Enumeration<InetAddress> getInetAddresses() {109return enumerationFromArray(getCheckedInetAddresses());110}111112/**113* Get a Stream of all or a subset of the InetAddresses bound to this114* network interface.115* <p>116* If there is a security manager, its {@code checkConnect}117* method is called for each InetAddress. Only InetAddresses where118* the {@code checkConnect} doesn't throw a SecurityException will be119* returned in the Stream. However, if the caller has the120* {@link NetPermission}("getNetworkInformation") permission, then all121* InetAddresses are returned.122*123* @return a Stream object with all or a subset of the InetAddresses124* bound to this network interface125* @since 9126*/127public Stream<InetAddress> inetAddresses() {128return streamFromArray(getCheckedInetAddresses());129}130131private InetAddress[] getCheckedInetAddresses() {132InetAddress[] local_addrs = new InetAddress[addrs.length];133boolean trusted = true;134135@SuppressWarnings("removal")136SecurityManager sec = System.getSecurityManager();137if (sec != null) {138try {139sec.checkPermission(new NetPermission("getNetworkInformation"));140} catch (SecurityException e) {141trusted = false;142}143}144int i = 0;145for (int j = 0; j < addrs.length; j++) {146try {147if (!trusted) {148sec.checkConnect(addrs[j].getHostAddress(), -1);149}150local_addrs[i++] = addrs[j];151} catch (SecurityException e) { }152}153return Arrays.copyOf(local_addrs, i);154}155156/**157* Get a List of all or a subset of the {@code InterfaceAddresses}158* of this network interface.159* <p>160* If there is a security manager, its {@code checkConnect}161* method is called with the InetAddress for each InterfaceAddress.162* Only InterfaceAddresses where the {@code checkConnect} doesn't throw163* a SecurityException will be returned in the List.164*165* @return a {@code List} object with all or a subset of the166* InterfaceAddress of this network interface167* @since 1.6168*/169public java.util.List<InterfaceAddress> getInterfaceAddresses() {170java.util.List<InterfaceAddress> lst = new java.util.ArrayList<>(1);171if (bindings != null) {172@SuppressWarnings("removal")173SecurityManager sec = System.getSecurityManager();174for (int j=0; j<bindings.length; j++) {175try {176if (sec != null) {177sec.checkConnect(bindings[j].getAddress().getHostAddress(), -1);178}179lst.add(bindings[j]);180} catch (SecurityException e) { }181}182}183return lst;184}185186/**187* Get an Enumeration with all the subinterfaces (also known as virtual188* interfaces) attached to this network interface.189* <p>190* For instance eth0:1 will be a subinterface to eth0.191*192* @return an Enumeration object with all of the subinterfaces193* of this network interface194* @see #subInterfaces()195* @since 1.6196*/197public Enumeration<NetworkInterface> getSubInterfaces() {198return enumerationFromArray(childs);199}200201/**202* Get a Stream of all subinterfaces (also known as virtual203* interfaces) attached to this network interface.204*205* @return a Stream object with all of the subinterfaces206* of this network interface207* @since 9208*/209public Stream<NetworkInterface> subInterfaces() {210return streamFromArray(childs);211}212213/**214* Returns the parent NetworkInterface of this interface if this is215* a subinterface, or {@code null} if it is a physical216* (non virtual) interface or has no parent.217*218* @return The {@code NetworkInterface} this interface is attached to.219* @since 1.6220*/221public NetworkInterface getParent() {222return parent;223}224225/**226* Returns the index of this network interface. The index is an integer greater227* or equal to zero, or {@code -1} for unknown. This is a system specific value228* and interfaces with the same name can have different indexes on different229* machines.230*231* @return the index of this network interface or {@code -1} if the index is232* unknown233* @see #getByIndex(int)234* @since 1.7235*/236public int getIndex() {237return index;238}239240/**241* Get the display name of this network interface.242* A display name is a human readable String describing the network243* device.244*245* @return a non-empty string representing the display name of this network246* interface, or null if no display name is available.247*/248public String getDisplayName() {249/* strict TCK conformance */250return "".equals(displayName) ? null : displayName;251}252253/**254* Searches for the network interface with the specified name.255*256* @param name257* The name of the network interface.258*259* @return A {@code NetworkInterface} with the specified name,260* or {@code null} if there is no network interface261* with the specified name.262*263* @throws SocketException264* If an I/O error occurs.265*266* @throws NullPointerException267* If the specified name is {@code null}.268*/269public static NetworkInterface getByName(String name) throws SocketException {270if (name == null)271throw new NullPointerException();272return getByName0(name);273}274275/**276* Get a network interface given its index.277*278* @param index an integer, the index of the interface279* @return the NetworkInterface obtained from its index, or {@code null} if280* there is no interface with such an index on the system281* @throws SocketException if an I/O error occurs.282* @throws IllegalArgumentException if index has a negative value283* @see #getIndex()284* @since 1.7285*/286public static NetworkInterface getByIndex(int index) throws SocketException {287if (index < 0)288throw new IllegalArgumentException("Interface index can't be negative");289return getByIndex0(index);290}291292/**293* Convenience method to search for a network interface that294* has the specified Internet Protocol (IP) address bound to295* it.296* <p>297* If the specified IP address is bound to multiple network298* interfaces it is not defined which network interface is299* returned.300*301* @param addr302* The {@code InetAddress} to search with.303*304* @return A {@code NetworkInterface}305* or {@code null} if there is no network interface306* with the specified IP address.307*308* @throws SocketException309* If an I/O error occurs.310*311* @throws NullPointerException312* If the specified address is {@code null}.313*/314public static NetworkInterface getByInetAddress(InetAddress addr) throws SocketException {315if (addr == null) {316throw new NullPointerException();317}318319if (addr.holder.family == InetAddress.IPv4) {320if (!(addr instanceof Inet4Address)) {321throw new IllegalArgumentException("invalid family type: "322+ addr.holder.family);323}324} else if (addr.holder.family == InetAddress.IPv6) {325if (!(addr instanceof Inet6Address)) {326throw new IllegalArgumentException("invalid family type: "327+ addr.holder.family);328}329} else {330throw new IllegalArgumentException("invalid address type: " + addr);331}332return getByInetAddress0(addr);333}334335/**336* Returns an {@code Enumeration} of all the interfaces on this machine. The337* {@code Enumeration} contains at least one element, possibly representing338* a loopback interface that only supports communication between entities on339* this machine.340*341* @apiNote this method can be used in combination with342* {@link #getInetAddresses()} to obtain all IP addresses for this node343*344* @return an Enumeration of NetworkInterfaces found on this machine345* @throws SocketException if an I/O error occurs,346* or if the platform does not have at least one configured347* network interface.348* @see #networkInterfaces()349*/350public static Enumeration<NetworkInterface> getNetworkInterfaces()351throws SocketException {352NetworkInterface[] netifs = getAll();353if (netifs != null && netifs.length > 0) {354return enumerationFromArray(netifs);355} else {356throw new SocketException("No network interfaces configured");357}358}359360/**361* Returns a {@code Stream} of all the interfaces on this machine. The362* {@code Stream} contains at least one interface, possibly representing a363* loopback interface that only supports communication between entities on364* this machine.365*366* @apiNote this method can be used in combination with367* {@link #inetAddresses()}} to obtain a stream of all IP addresses for368* this node, for example:369* <pre> {@code370* Stream<InetAddress> addrs = NetworkInterface.networkInterfaces()371* .flatMap(NetworkInterface::inetAddresses);372* }</pre>373*374* @return a Stream of NetworkInterfaces found on this machine375* @throws SocketException if an I/O error occurs,376* or if the platform does not have at least one configured377* network interface.378* @since 9379*/380public static Stream<NetworkInterface> networkInterfaces()381throws SocketException {382NetworkInterface[] netifs = getAll();383if (netifs != null && netifs.length > 0) {384return streamFromArray(netifs);385} else {386throw new SocketException("No network interfaces configured");387}388}389390/**391* Checks if the given address is bound to any of the interfaces on this392* machine.393*394* @param addr395* The {@code InetAddress} to search with.396* @return true iff the addr parameter is currently bound to one of397* the interfaces on this machine.398*399* @throws SocketException400* If an I/O error occurs.401*/402/* package-private */ static boolean isBoundInetAddress(InetAddress addr)403throws SocketException {404return boundInetAddress0(addr);405}406407private static <T> Enumeration<T> enumerationFromArray(T[] a) {408return new Enumeration<>() {409int i = 0;410411@Override412public T nextElement() {413if (i < a.length) {414return a[i++];415} else {416throw new NoSuchElementException();417}418}419420@Override421public boolean hasMoreElements() {422return i < a.length;423}424};425}426427private static <T> Stream<T> streamFromArray(T[] a) {428return StreamSupport.stream(429Spliterators.spliterator(430a,431Spliterator.DISTINCT | Spliterator.IMMUTABLE | Spliterator.NONNULL),432false);433}434435private static native NetworkInterface[] getAll()436throws SocketException;437438private static native NetworkInterface getByName0(String name)439throws SocketException;440441private static native NetworkInterface getByIndex0(int index)442throws SocketException;443444private static native boolean boundInetAddress0(InetAddress addr)445throws SocketException;446447private static native NetworkInterface getByInetAddress0(InetAddress addr)448throws SocketException;449450/**451* Returns whether a network interface is up and running.452*453* @return {@code true} if the interface is up and running.454* @throws SocketException if an I/O error occurs.455* @since 1.6456*/457458public boolean isUp() throws SocketException {459return isUp0(name, index);460}461462/**463* Returns whether a network interface is a loopback interface.464*465* @return {@code true} if the interface is a loopback interface.466* @throws SocketException if an I/O error occurs.467* @since 1.6468*/469470public boolean isLoopback() throws SocketException {471return isLoopback0(name, index);472}473474/**475* Returns whether a network interface is a point to point interface.476* A typical point to point interface would be a PPP connection through477* a modem.478*479* @return {@code true} if the interface is a point to point480* interface.481* @throws SocketException if an I/O error occurs.482* @since 1.6483*/484485public boolean isPointToPoint() throws SocketException {486return isP2P0(name, index);487}488489/**490* Returns whether a network interface supports multicasting or not.491*492* @return {@code true} if the interface supports Multicasting.493* @throws SocketException if an I/O error occurs.494* @since 1.6495*/496497public boolean supportsMulticast() throws SocketException {498return supportsMulticast0(name, index);499}500501/**502* Returns the hardware address (usually MAC) of the interface if it503* has one and if it can be accessed given the current privileges.504* If a security manager is set, then the caller must have505* the permission {@link NetPermission}("getNetworkInformation").506*507* @return a byte array containing the address, or {@code null} if508* the address doesn't exist, is not accessible or a security509* manager is set and the caller does not have the permission510* NetPermission("getNetworkInformation")511*512* @throws SocketException if an I/O error occurs.513* @since 1.6514*/515public byte[] getHardwareAddress() throws SocketException {516@SuppressWarnings("removal")517SecurityManager sec = System.getSecurityManager();518if (sec != null) {519try {520sec.checkPermission(new NetPermission("getNetworkInformation"));521} catch (SecurityException e) {522if (!getInetAddresses().hasMoreElements()) {523// don't have connect permission to any local address524return null;525}526}527}528if (isLoopback0(name, index)) {529return null;530}531for (InetAddress addr : addrs) {532if (addr instanceof Inet4Address) {533return getMacAddr0(((Inet4Address)addr).getAddress(), name, index);534}535}536return getMacAddr0(null, name, index);537}538539/**540* Returns the Maximum Transmission Unit (MTU) of this interface.541*542* @return the value of the MTU for that interface.543* @throws SocketException if an I/O error occurs.544* @since 1.6545*/546public int getMTU() throws SocketException {547return getMTU0(name, index);548}549550/**551* Returns whether this interface is a virtual interface (also called552* subinterface).553* Virtual interfaces are, on some systems, interfaces created as a child554* of a physical interface and given different settings (like address or555* MTU). Usually the name of the interface will the name of the parent556* followed by a colon (:) and a number identifying the child since there557* can be several virtual interfaces attached to a single physical558* interface.559*560* @return {@code true} if this interface is a virtual interface.561* @since 1.6562*/563public boolean isVirtual() {564return virtual;565}566567private static native boolean isUp0(String name, int ind) throws SocketException;568private static native boolean isLoopback0(String name, int ind) throws SocketException;569private static native boolean supportsMulticast0(String name, int ind) throws SocketException;570private static native boolean isP2P0(String name, int ind) throws SocketException;571private static native byte[] getMacAddr0(byte[] inAddr, String name, int ind) throws SocketException;572private static native int getMTU0(String name, int ind) throws SocketException;573574/**575* Compares this object against the specified object.576* The result is {@code true} if and only if the argument is577* not {@code null} and it represents the same NetworkInterface578* as this object.579* <p>580* Two instances of {@code NetworkInterface} represent the same581* NetworkInterface if both the name and the set of {@code InetAddress}es582* bound to the interfaces are equal.583*584* @apiNote two {@code NetworkInterface} objects referring to the same585* underlying interface may not compare equal if the addresses586* of the underlying interface are being dynamically updated by587* the system.588*589* @param obj the object to compare against.590* @return {@code true} if the objects are the same;591* {@code false} otherwise.592* @see java.net.InetAddress#getAddress()593*/594public boolean equals(Object obj) {595if (!(obj instanceof NetworkInterface that)) {596return false;597}598if (this.name != null ) {599if (!this.name.equals(that.name)) {600return false;601}602} else {603if (that.name != null) {604return false;605}606}607608if (this.addrs == null) {609return that.addrs == null;610} else if (that.addrs == null) {611return false;612}613614/* Both addrs not null. Compare number of addresses */615616if (this.addrs.length != that.addrs.length) {617return false;618}619620InetAddress[] thatAddrs = that.addrs;621int count = thatAddrs.length;622623for (int i=0; i<count; i++) {624boolean found = false;625for (int j=0; j<count; j++) {626if (addrs[i].equals(thatAddrs[j])) {627found = true;628break;629}630}631if (!found) {632return false;633}634}635return true;636}637638public int hashCode() {639return name == null? 0: name.hashCode();640}641642public String toString() {643String result = "name:";644result += name == null? "null": name;645if (displayName != null) {646result += " (" + displayName + ")";647}648return result;649}650651private static native void init();652653/**654* Returns the default network interface of this system655*656* @return the default interface657*/658static NetworkInterface getDefault() {659return defaultInterface;660}661}662663664