Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/net/NetworkInterface.java
38829 views
/*1* Copyright (c) 2000, 2018, 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.Enumeration;28import java.util.NoSuchElementException;29import sun.security.action.*;30import java.security.AccessController;3132/**33* This class represents a Network Interface made up of a name,34* and a list of IP addresses assigned to this interface.35* It is used to identify the local interface on which a multicast group36* is joined.37*38* Interfaces are normally known by names such as "le0".39*40* @since 1.441*/42public final class NetworkInterface {43private String name;44private String displayName;45private int index;46private InetAddress addrs[];47private InterfaceAddress bindings[];48private NetworkInterface childs[];49private NetworkInterface parent = null;50private boolean virtual = false;51private static final NetworkInterface defaultInterface;52private static final int defaultIndex; /* index of defaultInterface */5354static {55AccessController.doPrivileged(56new java.security.PrivilegedAction<Void>() {57public Void run() {58System.loadLibrary("net");59return null;60}61});6263init();64defaultInterface = DefaultInterface.getDefault();65if (defaultInterface != null) {66defaultIndex = defaultInterface.getIndex();67} else {68defaultIndex = 0;69}70}7172/**73* Returns an NetworkInterface object with index set to 0 and name to null.74* Setting such an interface on a MulticastSocket will cause the75* kernel to choose one interface for sending multicast packets.76*77*/78NetworkInterface() {79}8081NetworkInterface(String name, int index, InetAddress[] addrs) {82this.name = name;83this.index = index;84this.addrs = addrs;85}8687/**88* Get the name of this network interface.89*90* @return the name of this network interface91*/92public String getName() {93return name;94}9596/**97* Convenience method to return an Enumeration with all or a98* subset of the InetAddresses bound to this network interface.99* <p>100* If there is a security manager, its {@code checkConnect}101* method is called for each InetAddress. Only InetAddresses where102* the {@code checkConnect} doesn't throw a SecurityException103* will be returned in the Enumeration. However, if the caller has the104* {@link NetPermission}("getNetworkInformation") permission, then all105* InetAddresses are returned.106* @return an Enumeration object with all or a subset of the InetAddresses107* bound to this network interface108*/109public Enumeration<InetAddress> getInetAddresses() {110111class checkedAddresses implements Enumeration<InetAddress> {112113private int i=0, count=0;114private InetAddress local_addrs[];115116checkedAddresses() {117local_addrs = new InetAddress[addrs.length];118boolean trusted = true;119120SecurityManager sec = System.getSecurityManager();121if (sec != null) {122try {123sec.checkPermission(new NetPermission("getNetworkInformation"));124} catch (SecurityException e) {125trusted = false;126}127}128for (int j=0; j<addrs.length; j++) {129try {130if (sec != null && !trusted) {131sec.checkConnect(addrs[j].getHostAddress(), -1);132}133local_addrs[count++] = addrs[j];134} catch (SecurityException e) { }135}136137}138139public InetAddress nextElement() {140if (i < count) {141return local_addrs[i++];142} else {143throw new NoSuchElementException();144}145}146147public boolean hasMoreElements() {148return (i < count);149}150}151return new checkedAddresses();152153}154155/**156* Get a List of all or a subset of the {@code InterfaceAddresses}157* of this network interface.158* <p>159* If there is a security manager, its {@code checkConnect}160* method is called with the InetAddress for each InterfaceAddress.161* Only InterfaceAddresses where the {@code checkConnect} doesn't throw162* a SecurityException will be returned in the List.163*164* @return a {@code List} object with all or a subset of the165* InterfaceAddresss of this network interface166* @since 1.6167*/168public java.util.List<InterfaceAddress> getInterfaceAddresses() {169java.util.List<InterfaceAddress> lst = new java.util.ArrayList<InterfaceAddress>(1);170SecurityManager sec = System.getSecurityManager();171for (int j=0; j<bindings.length; j++) {172try {173if (sec != null) {174sec.checkConnect(bindings[j].getAddress().getHostAddress(), -1);175}176lst.add(bindings[j]);177} catch (SecurityException e) { }178}179return lst;180}181182/**183* Get an Enumeration with all the subinterfaces (also known as virtual184* interfaces) attached to this network interface.185* <p>186* For instance eth0:1 will be a subinterface to eth0.187*188* @return an Enumeration object with all of the subinterfaces189* of this network interface190* @since 1.6191*/192public Enumeration<NetworkInterface> getSubInterfaces() {193class subIFs implements Enumeration<NetworkInterface> {194195private int i=0;196197subIFs() {198}199200public NetworkInterface nextElement() {201if (i < childs.length) {202return childs[i++];203} else {204throw new NoSuchElementException();205}206}207208public boolean hasMoreElements() {209return (i < childs.length);210}211}212return new subIFs();213214}215216/**217* Returns the parent NetworkInterface of this interface if this is218* a subinterface, or {@code null} if it is a physical219* (non virtual) interface or has no parent.220*221* @return The {@code NetworkInterface} this interface is attached to.222* @since 1.6223*/224public NetworkInterface getParent() {225return parent;226}227228/**229* Returns the index of this network interface. The index is an integer greater230* or equal to zero, or {@code -1} for unknown. This is a system specific value231* and interfaces with the same name can have different indexes on different232* machines.233*234* @return the index of this network interface or {@code -1} if the index is235* unknown236* @see #getByIndex(int)237* @since 1.7238*/239public int getIndex() {240return index;241}242243/**244* Get the display name of this network interface.245* A display name is a human readable String describing the network246* device.247*248* @return a non-empty string representing the display name of this network249* interface, or null if no display name is available.250*/251public String getDisplayName() {252/* strict TCK conformance */253return "".equals(displayName) ? null : displayName;254}255256/**257* Searches for the network interface with the specified name.258*259* @param name260* The name of the network interface.261*262* @return A {@code NetworkInterface} with the specified name,263* or {@code null} if there is no network interface264* with the specified name.265*266* @throws SocketException267* If an I/O error occurs.268*269* @throws NullPointerException270* If the specified name is {@code null}.271*/272public static NetworkInterface getByName(String name) throws SocketException {273if (name == null)274throw new NullPointerException();275return getByName0(name);276}277278/**279* Get a network interface given its index.280*281* @param index an integer, the index of the interface282* @return the NetworkInterface obtained from its index, or {@code null} if283* there is no interface with such an index on the system284* @throws SocketException if an I/O error occurs.285* @throws IllegalArgumentException if index has a negative value286* @see #getIndex()287* @since 1.7288*/289public static NetworkInterface getByIndex(int index) throws SocketException {290if (index < 0)291throw new IllegalArgumentException("Interface index can't be negative");292return getByIndex0(index);293}294295/**296* Convenience method to search for a network interface that297* has the specified Internet Protocol (IP) address bound to298* it.299* <p>300* If the specified IP address is bound to multiple network301* interfaces it is not defined which network interface is302* returned.303*304* @param addr305* The {@code InetAddress} to search with.306*307* @return A {@code NetworkInterface}308* or {@code null} if there is no network interface309* with the specified IP address.310*311* @throws SocketException312* If an I/O error occurs.313*314* @throws NullPointerException315* If the specified address is {@code null}.316*/317public static NetworkInterface getByInetAddress(InetAddress addr) throws SocketException {318if (addr == null) {319throw new NullPointerException();320}321if (addr instanceof Inet4Address) {322Inet4Address inet4Address = (Inet4Address) addr;323if (inet4Address.holder.family != InetAddress.IPv4) {324throw new IllegalArgumentException("invalid family type: "325+ inet4Address.holder.family);326}327} else if (addr instanceof Inet6Address) {328Inet6Address inet6Address = (Inet6Address) addr;329if (inet6Address.holder.family != InetAddress.IPv6) {330throw new IllegalArgumentException("invalid family type: "331+ inet6Address.holder.family);332}333} else {334throw new IllegalArgumentException("invalid address type: " + addr);335}336return getByInetAddress0(addr);337}338339/**340* Returns all the interfaces on this machine. The {@code Enumeration}341* contains at least one element, possibly representing a loopback342* interface that only supports communication between entities on343* this machine.344*345* NOTE: can use getNetworkInterfaces()+getInetAddresses()346* to obtain all IP addresses for this node347*348* @return an Enumeration of NetworkInterfaces found on this machine349* @exception SocketException if an I/O error occurs.350*/351352public static Enumeration<NetworkInterface> getNetworkInterfaces()353throws SocketException {354final NetworkInterface[] netifs = getAll();355356// specified to return null if no network interfaces357if (netifs == null)358return null;359360return new Enumeration<NetworkInterface>() {361private int i = 0;362public NetworkInterface nextElement() {363if (netifs != null && i < netifs.length) {364NetworkInterface netif = netifs[i++];365return netif;366} else {367throw new NoSuchElementException();368}369}370371public boolean hasMoreElements() {372return (netifs != null && i < netifs.length);373}374};375}376377private native static NetworkInterface[] getAll()378throws SocketException;379380private native static NetworkInterface getByName0(String name)381throws SocketException;382383private native static NetworkInterface getByIndex0(int index)384throws SocketException;385386private native static NetworkInterface getByInetAddress0(InetAddress addr)387throws SocketException;388389/**390* Returns whether a network interface is up and running.391*392* @return {@code true} if the interface is up and running.393* @exception SocketException if an I/O error occurs.394* @since 1.6395*/396397public boolean isUp() throws SocketException {398return isUp0(name, index);399}400401/**402* Returns whether a network interface is a loopback interface.403*404* @return {@code true} if the interface is a loopback interface.405* @exception SocketException if an I/O error occurs.406* @since 1.6407*/408409public boolean isLoopback() throws SocketException {410return isLoopback0(name, index);411}412413/**414* Returns whether a network interface is a point to point interface.415* A typical point to point interface would be a PPP connection through416* a modem.417*418* @return {@code true} if the interface is a point to point419* interface.420* @exception SocketException if an I/O error occurs.421* @since 1.6422*/423424public boolean isPointToPoint() throws SocketException {425return isP2P0(name, index);426}427428/**429* Returns whether a network interface supports multicasting or not.430*431* @return {@code true} if the interface supports Multicasting.432* @exception SocketException if an I/O error occurs.433* @since 1.6434*/435436public boolean supportsMulticast() throws SocketException {437return supportsMulticast0(name, index);438}439440/**441* Returns the hardware address (usually MAC) of the interface if it442* has one and if it can be accessed given the current privileges.443* If a security manager is set, then the caller must have444* the permission {@link NetPermission}("getNetworkInformation").445*446* @return a byte array containing the address, or {@code null} if447* the address doesn't exist, is not accessible or a security448* manager is set and the caller does not have the permission449* NetPermission("getNetworkInformation")450*451* @exception SocketException if an I/O error occurs.452* @since 1.6453*/454public byte[] getHardwareAddress() throws SocketException {455SecurityManager sec = System.getSecurityManager();456if (sec != null) {457try {458sec.checkPermission(new NetPermission("getNetworkInformation"));459} catch (SecurityException e) {460if (!getInetAddresses().hasMoreElements()) {461// don't have connect permission to any local address462return null;463}464}465}466for (InetAddress addr : addrs) {467if (addr instanceof Inet4Address) {468return getMacAddr0(((Inet4Address)addr).getAddress(), name, index);469}470}471return getMacAddr0(null, name, index);472}473474/**475* Returns the Maximum Transmission Unit (MTU) of this interface.476*477* @return the value of the MTU for that interface.478* @exception SocketException if an I/O error occurs.479* @since 1.6480*/481public int getMTU() throws SocketException {482return getMTU0(name, index);483}484485/**486* Returns whether this interface is a virtual interface (also called487* subinterface).488* Virtual interfaces are, on some systems, interfaces created as a child489* of a physical interface and given different settings (like address or490* MTU). Usually the name of the interface will the name of the parent491* followed by a colon (:) and a number identifying the child since there492* can be several virtual interfaces attached to a single physical493* interface.494*495* @return {@code true} if this interface is a virtual interface.496* @since 1.6497*/498public boolean isVirtual() {499return virtual;500}501502private native static boolean isUp0(String name, int ind) throws SocketException;503private native static boolean isLoopback0(String name, int ind) throws SocketException;504private native static boolean supportsMulticast0(String name, int ind) throws SocketException;505private native static boolean isP2P0(String name, int ind) throws SocketException;506private native static byte[] getMacAddr0(byte[] inAddr, String name, int ind) throws SocketException;507private native static int getMTU0(String name, int ind) throws SocketException;508509/**510* Compares this object against the specified object.511* The result is {@code true} if and only if the argument is512* not {@code null} and it represents the same NetworkInterface513* as this object.514* <p>515* Two instances of {@code NetworkInterface} represent the same516* NetworkInterface if both name and addrs are the same for both.517*518* @param obj the object to compare against.519* @return {@code true} if the objects are the same;520* {@code false} otherwise.521* @see java.net.InetAddress#getAddress()522*/523public boolean equals(Object obj) {524if (!(obj instanceof NetworkInterface)) {525return false;526}527NetworkInterface that = (NetworkInterface)obj;528if (this.name != null ) {529if (!this.name.equals(that.name)) {530return false;531}532} else {533if (that.name != null) {534return false;535}536}537538if (this.addrs == null) {539return that.addrs == null;540} else if (that.addrs == null) {541return false;542}543544/* Both addrs not null. Compare number of addresses */545546if (this.addrs.length != that.addrs.length) {547return false;548}549550InetAddress[] thatAddrs = that.addrs;551int count = thatAddrs.length;552553for (int i=0; i<count; i++) {554boolean found = false;555for (int j=0; j<count; j++) {556if (addrs[i].equals(thatAddrs[j])) {557found = true;558break;559}560}561if (!found) {562return false;563}564}565return true;566}567568public int hashCode() {569return name == null? 0: name.hashCode();570}571572public String toString() {573String result = "name:";574result += name == null? "null": name;575if (displayName != null) {576result += " (" + displayName + ")";577}578return result;579}580581private static native void init();582583/**584* Returns the default network interface of this system585*586* @return the default interface587*/588static NetworkInterface getDefault() {589return defaultInterface;590}591}592593594