1 /*
   2  * Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.net;
  27 
  28 import java.util.Arrays;
  29 import java.util.Enumeration;
  30 import java.util.NoSuchElementException;
  31 import java.security.AccessController;
  32 import java.util.Spliterator;
  33 import java.util.Spliterators;
  34 import java.util.stream.Stream;
  35 import java.util.stream.StreamSupport;
  36 
  37 /**
  38  * This class represents a Network Interface made up of a name,
  39  * and a list of IP addresses assigned to this interface.
  40  * It is used to identify the local interface on which a multicast group
  41  * is joined.
  42  *
  43  * Interfaces are normally known by names such as "le0".
  44  *
  45  * @since 1.4
  46  */
  47 public final class NetworkInterface {
  48     private String name;
  49     private String displayName;
  50     private int index;
  51     private InetAddress addrs[];
  52     private InterfaceAddress bindings[];
  53     private NetworkInterface childs[];
  54     private NetworkInterface parent = null;
  55     private boolean virtual = false;
  56     private static final NetworkInterface defaultInterface;
  57     private static final int defaultIndex; /* index of defaultInterface */
  58 
  59     static {
  60         AccessController.doPrivileged(
  61             new java.security.PrivilegedAction<>() {
  62                 public Void run() {
  63                     System.loadLibrary("net");
  64                     return null;
  65                 }
  66             });
  67 
  68         init();
  69         defaultInterface = DefaultInterface.getDefault();
  70         if (defaultInterface != null) {
  71             defaultIndex = defaultInterface.getIndex();
  72         } else {
  73             defaultIndex = 0;
  74         }
  75     }
  76 
  77     /**
  78      * Returns an NetworkInterface object with index set to 0 and name to null.
  79      * Setting such an interface on a MulticastSocket will cause the
  80      * kernel to choose one interface for sending multicast packets.
  81      *
  82      */
  83     NetworkInterface() {
  84     }
  85 
  86     NetworkInterface(String name, int index, InetAddress[] addrs) {
  87         this.name = name;
  88         this.index = index;
  89         this.addrs = addrs;
  90     }
  91 
  92     /**
  93      * Get the name of this network interface.
  94      *
  95      * @return the name of this network interface
  96      */
  97     public String getName() {
  98             return name;
  99     }
 100 
 101     /**
 102      * Get an Enumeration with all or a subset of the InetAddresses bound to
 103      * this network interface.
 104      * <p>
 105      * If there is a security manager, its {@code checkConnect}
 106      * method is called for each InetAddress. Only InetAddresses where
 107      * the {@code checkConnect} doesn't throw a SecurityException
 108      * will be returned in the Enumeration. However, if the caller has the
 109      * {@link NetPermission}("getNetworkInformation") permission, then all
 110      * InetAddresses are returned.
 111      *
 112      * @return an Enumeration object with all or a subset of the InetAddresses
 113      * bound to this network interface
 114      * @see #inetAddresses()
 115      */
 116     public Enumeration<InetAddress> getInetAddresses() {
 117         return enumerationFromArray(getCheckedInetAddresses());
 118     }
 119 
 120     /**
 121      * Get a Stream of all or a subset of the InetAddresses bound to this
 122      * network interface.
 123      * <p>
 124      * If there is a security manager, its {@code checkConnect}
 125      * method is called for each InetAddress. Only InetAddresses where
 126      * the {@code checkConnect} doesn't throw a SecurityException will be
 127      * returned in the Stream. However, if the caller has the
 128      * {@link NetPermission}("getNetworkInformation") permission, then all
 129      * InetAddresses are returned.
 130      *
 131      * @return a Stream object with all or a subset of the InetAddresses
 132      * bound to this network interface
 133      * @since 9
 134      */
 135     public Stream<InetAddress> inetAddresses() {
 136         return streamFromArray(getCheckedInetAddresses());
 137     }
 138 
 139     private InetAddress[] getCheckedInetAddresses() {
 140         InetAddress[] local_addrs = new InetAddress[addrs.length];
 141         boolean trusted = true;
 142 
 143         SecurityManager sec = System.getSecurityManager();
 144         if (sec != null) {
 145             try {
 146                 sec.checkPermission(new NetPermission("getNetworkInformation"));
 147             } catch (SecurityException e) {
 148                 trusted = false;
 149             }
 150         }
 151         int i = 0;
 152         for (int j = 0; j < addrs.length; j++) {
 153             try {
 154                 if (!trusted) {
 155                     sec.checkConnect(addrs[j].getHostAddress(), -1);
 156                 }
 157                 local_addrs[i++] = addrs[j];
 158             } catch (SecurityException e) { }
 159         }
 160         return Arrays.copyOf(local_addrs, i);
 161     }
 162 
 163     /**
 164      * Get a List of all or a subset of the {@code InterfaceAddresses}
 165      * of this network interface.
 166      * <p>
 167      * If there is a security manager, its {@code checkConnect}
 168      * method is called with the InetAddress for each InterfaceAddress.
 169      * Only InterfaceAddresses where the {@code checkConnect} doesn't throw
 170      * a SecurityException will be returned in the List.
 171      *
 172      * @return a {@code List} object with all or a subset of the
 173      *         InterfaceAddress of this network interface
 174      * @since 1.6
 175      */
 176     public java.util.List<InterfaceAddress> getInterfaceAddresses() {
 177         java.util.List<InterfaceAddress> lst = new java.util.ArrayList<>(1);
 178         if (bindings != null) {
 179             SecurityManager sec = System.getSecurityManager();
 180             for (int j=0; j<bindings.length; j++) {
 181                 try {
 182                     if (sec != null) {
 183                         sec.checkConnect(bindings[j].getAddress().getHostAddress(), -1);
 184                     }
 185                     lst.add(bindings[j]);
 186                 } catch (SecurityException e) { }
 187             }
 188         }
 189         return lst;
 190     }
 191 
 192     /**
 193      * Get an Enumeration with all the subinterfaces (also known as virtual
 194      * interfaces) attached to this network interface.
 195      * <p>
 196      * For instance eth0:1 will be a subinterface to eth0.
 197      *
 198      * @return an Enumeration object with all of the subinterfaces
 199      * of this network interface
 200      * @see #subInterfaces()
 201      * @since 1.6
 202      */
 203     public Enumeration<NetworkInterface> getSubInterfaces() {
 204         return enumerationFromArray(childs);
 205     }
 206 
 207     /**
 208      * Get a Stream of all subinterfaces (also known as virtual
 209      * interfaces) attached to this network interface.
 210      *
 211      * @return a Stream object with all of the subinterfaces
 212      * of this network interface
 213      * @since 9
 214      */
 215     public Stream<NetworkInterface> subInterfaces() {
 216         return streamFromArray(childs);
 217     }
 218 
 219     /**
 220      * Returns the parent NetworkInterface of this interface if this is
 221      * a subinterface, or {@code null} if it is a physical
 222      * (non virtual) interface or has no parent.
 223      *
 224      * @return The {@code NetworkInterface} this interface is attached to.
 225      * @since 1.6
 226      */
 227     public NetworkInterface getParent() {
 228         return parent;
 229     }
 230 
 231     /**
 232      * Returns the index of this network interface. The index is an integer greater
 233      * or equal to zero, or {@code -1} for unknown. This is a system specific value
 234      * and interfaces with the same name can have different indexes on different
 235      * machines.
 236      *
 237      * @return the index of this network interface or {@code -1} if the index is
 238      *         unknown
 239      * @see #getByIndex(int)
 240      * @since 1.7
 241      */
 242     public int getIndex() {
 243         return index;
 244     }
 245 
 246     /**
 247      * Get the display name of this network interface.
 248      * A display name is a human readable String describing the network
 249      * device.
 250      *
 251      * @return a non-empty string representing the display name of this network
 252      *         interface, or null if no display name is available.
 253      */
 254     public String getDisplayName() {
 255         /* strict TCK conformance */
 256         return "".equals(displayName) ? null : displayName;
 257     }
 258 
 259     /**
 260      * Searches for the network interface with the specified name.
 261      *
 262      * @param   name
 263      *          The name of the network interface.
 264      *
 265      * @return  A {@code NetworkInterface} with the specified name,
 266      *          or {@code null} if there is no network interface
 267      *          with the specified name.
 268      *
 269      * @throws  SocketException
 270      *          If an I/O error occurs.
 271      *
 272      * @throws  NullPointerException
 273      *          If the specified name is {@code null}.
 274      */
 275     public static NetworkInterface getByName(String name) throws SocketException {
 276         if (name == null)
 277             throw new NullPointerException();
 278         return getByName0(name);
 279     }
 280 
 281     /**
 282      * Get a network interface given its index.
 283      *
 284      * @param index an integer, the index of the interface
 285      * @return the NetworkInterface obtained from its index, or {@code null} if
 286      *         there is no interface with such an index on the system
 287      * @throws  SocketException  if an I/O error occurs.
 288      * @throws  IllegalArgumentException if index has a negative value
 289      * @see #getIndex()
 290      * @since 1.7
 291      */
 292     public static NetworkInterface getByIndex(int index) throws SocketException {
 293         if (index < 0)
 294             throw new IllegalArgumentException("Interface index can't be negative");
 295         return getByIndex0(index);
 296     }
 297 
 298     /**
 299      * Convenience method to search for a network interface that
 300      * has the specified Internet Protocol (IP) address bound to
 301      * it.
 302      * <p>
 303      * If the specified IP address is bound to multiple network
 304      * interfaces it is not defined which network interface is
 305      * returned.
 306      *
 307      * @param   addr
 308      *          The {@code InetAddress} to search with.
 309      *
 310      * @return  A {@code NetworkInterface}
 311      *          or {@code null} if there is no network interface
 312      *          with the specified IP address.
 313      *
 314      * @throws  SocketException
 315      *          If an I/O error occurs.
 316      *
 317      * @throws  NullPointerException
 318      *          If the specified address is {@code null}.
 319      */
 320     public static NetworkInterface getByInetAddress(InetAddress addr) throws SocketException {
 321         if (addr == null) {
 322             throw new NullPointerException();
 323         }
 324 
 325         if (addr.holder.family == InetAddress.IPv4) {
 326             if (!(addr instanceof Inet4Address)) {
 327                 throw new IllegalArgumentException("invalid family type: "
 328                         + addr.holder.family);
 329             }
 330         } else if (addr.holder.family == InetAddress.IPv6) {
 331             if (!(addr instanceof Inet6Address)) {
 332                 throw new IllegalArgumentException("invalid family type: "
 333                         + addr.holder.family);
 334             }
 335         } else {
 336             throw new IllegalArgumentException("invalid address type: " + addr);
 337         }
 338         return getByInetAddress0(addr);
 339     }
 340 
 341     /**
 342      * Returns an {@code Enumeration} of all the interfaces on this machine. The
 343      * {@code Enumeration} contains at least one element, possibly representing
 344      * a loopback interface that only supports communication between entities on
 345      * this machine.
 346      *
 347      * @apiNote this method can be used in combination with
 348      * {@link #getInetAddresses()} to obtain all IP addresses for this node
 349      *
 350      * @return an Enumeration of NetworkInterfaces found on this machine
 351      * @exception  SocketException  if an I/O error occurs,
 352      *             or if the platform does not have at least one configured
 353      *             network interface.
 354      * @see #networkInterfaces()
 355      */
 356     public static Enumeration<NetworkInterface> getNetworkInterfaces()
 357         throws SocketException {
 358         NetworkInterface[] netifs = getAll();
 359         if (netifs != null && netifs.length > 0) {
 360             return enumerationFromArray(netifs);
 361         } else {
 362             throw new SocketException("No network interfaces configured");
 363         }
 364     }
 365 
 366     /**
 367      * Returns a {@code Stream} of all the interfaces on this machine.  The
 368      * {@code Stream} contains at least one interface, possibly representing a
 369      * loopback interface that only supports communication between entities on
 370      * this machine.
 371      *
 372      * @apiNote this method can be used in combination with
 373      * {@link #inetAddresses()}} to obtain a stream of all IP addresses for
 374      * this node, for example:
 375      * <pre> {@code
 376      * Stream<InetAddress> addrs = NetworkInterface.networkInterfaces()
 377      *     .flatMap(NetworkInterface::inetAddresses);
 378      * }</pre>
 379      *
 380      * @return a Stream of NetworkInterfaces found on this machine
 381      * @exception  SocketException  if an I/O error occurs,
 382      *             or if the platform does not have at least one configured
 383      *             network interface.
 384      * @since 9
 385      */
 386     public static Stream<NetworkInterface> networkInterfaces()
 387         throws SocketException {
 388         NetworkInterface[] netifs = getAll();
 389         if (netifs != null && netifs.length > 0) {
 390             return streamFromArray(netifs);
 391         }  else {
 392             throw new SocketException("No network interfaces configured");
 393         }
 394     }
 395 
 396     /**
 397      * Checks if the given address is bound to any of the interfaces on this
 398      * machine.
 399      *
 400      * @param   addr
 401      *          The {@code InetAddress} to search with.
 402      * @return  true iff the addr parameter is currently bound to one of
 403      *          the interfaces on this machine.
 404      *
 405      * @throws  SocketException
 406      *          If an I/O error occurs.
 407      */
 408     /* package-private */ static boolean isBoundInetAddress(InetAddress addr)
 409         throws SocketException {
 410         return boundInetAddress0(addr);
 411     }
 412 
 413     private static <T> Enumeration<T> enumerationFromArray(T[] a) {
 414         return new Enumeration<>() {
 415             int i = 0;
 416 
 417             @Override
 418             public T nextElement() {
 419                 if (i < a.length) {
 420                     return a[i++];
 421                 } else {
 422                     throw new NoSuchElementException();
 423                 }
 424             }
 425 
 426             @Override
 427             public boolean hasMoreElements() {
 428                 return i < a.length;
 429             }
 430         };
 431     }
 432 
 433     private static <T> Stream<T> streamFromArray(T[] a) {
 434         return StreamSupport.stream(
 435                 Spliterators.spliterator(
 436                         a,
 437                         Spliterator.DISTINCT | Spliterator.IMMUTABLE | Spliterator.NONNULL),
 438                 false);
 439     }
 440 
 441     private static native NetworkInterface[] getAll()
 442         throws SocketException;
 443 
 444     private static native NetworkInterface getByName0(String name)
 445         throws SocketException;
 446 
 447     private static native NetworkInterface getByIndex0(int index)
 448         throws SocketException;
 449 
 450     private static native boolean boundInetAddress0(InetAddress addr)
 451             throws SocketException;
 452 
 453     private static native NetworkInterface getByInetAddress0(InetAddress addr)
 454         throws SocketException;
 455 
 456     /**
 457      * Returns whether a network interface is up and running.
 458      *
 459      * @return  {@code true} if the interface is up and running.
 460      * @exception       SocketException if an I/O error occurs.
 461      * @since 1.6
 462      */
 463 
 464     public boolean isUp() throws SocketException {
 465         return isUp0(name, index);
 466     }
 467 
 468     /**
 469      * Returns whether a network interface is a loopback interface.
 470      *
 471      * @return  {@code true} if the interface is a loopback interface.
 472      * @exception       SocketException if an I/O error occurs.
 473      * @since 1.6
 474      */
 475 
 476     public boolean isLoopback() throws SocketException {
 477         return isLoopback0(name, index);
 478     }
 479 
 480     /**
 481      * Returns whether a network interface is a point to point interface.
 482      * A typical point to point interface would be a PPP connection through
 483      * a modem.
 484      *
 485      * @return  {@code true} if the interface is a point to point
 486      *          interface.
 487      * @exception       SocketException if an I/O error occurs.
 488      * @since 1.6
 489      */
 490 
 491     public boolean isPointToPoint() throws SocketException {
 492         return isP2P0(name, index);
 493     }
 494 
 495     /**
 496      * Returns whether a network interface supports multicasting or not.
 497      *
 498      * @return  {@code true} if the interface supports Multicasting.
 499      * @exception       SocketException if an I/O error occurs.
 500      * @since 1.6
 501      */
 502 
 503     public boolean supportsMulticast() throws SocketException {
 504         return supportsMulticast0(name, index);
 505     }
 506 
 507     /**
 508      * Returns the hardware address (usually MAC) of the interface if it
 509      * has one and if it can be accessed given the current privileges.
 510      * If a security manager is set, then the caller must have
 511      * the permission {@link NetPermission}("getNetworkInformation").
 512      *
 513      * @return  a byte array containing the address, or {@code null} if
 514      *          the address doesn't exist, is not accessible or a security
 515      *          manager is set and the caller does not have the permission
 516      *          NetPermission("getNetworkInformation")
 517      *
 518      * @exception       SocketException if an I/O error occurs.
 519      * @since 1.6
 520      */
 521     public byte[] getHardwareAddress() throws SocketException {
 522         SecurityManager sec = System.getSecurityManager();
 523         if (sec != null) {
 524             try {
 525                 sec.checkPermission(new NetPermission("getNetworkInformation"));
 526             } catch (SecurityException e) {
 527                 if (!getInetAddresses().hasMoreElements()) {
 528                     // don't have connect permission to any local address
 529                     return null;
 530                 }
 531             }
 532         }
 533         for (InetAddress addr : addrs) {
 534             if (addr instanceof Inet4Address) {
 535                 return getMacAddr0(((Inet4Address)addr).getAddress(), name, index);
 536             }
 537         }
 538         return getMacAddr0(null, name, index);
 539     }
 540 
 541     /**
 542      * Returns the Maximum Transmission Unit (MTU) of this interface.
 543      *
 544      * @return the value of the MTU for that interface.
 545      * @exception       SocketException if an I/O error occurs.
 546      * @since 1.6
 547      */
 548     public int getMTU() throws SocketException {
 549         return getMTU0(name, index);
 550     }
 551 
 552     /**
 553      * Returns whether this interface is a virtual interface (also called
 554      * subinterface).
 555      * Virtual interfaces are, on some systems, interfaces created as a child
 556      * of a physical interface and given different settings (like address or
 557      * MTU). Usually the name of the interface will the name of the parent
 558      * followed by a colon (:) and a number identifying the child since there
 559      * can be several virtual interfaces attached to a single physical
 560      * interface.
 561      *
 562      * @return {@code true} if this interface is a virtual interface.
 563      * @since 1.6
 564      */
 565     public boolean isVirtual() {
 566         return virtual;
 567     }
 568 
 569     private static native boolean isUp0(String name, int ind) throws SocketException;
 570     private static native boolean isLoopback0(String name, int ind) throws SocketException;
 571     private static native boolean supportsMulticast0(String name, int ind) throws SocketException;
 572     private static native boolean isP2P0(String name, int ind) throws SocketException;
 573     private static native byte[] getMacAddr0(byte[] inAddr, String name, int ind) throws SocketException;
 574     private static native int getMTU0(String name, int ind) throws SocketException;
 575 
 576     /**
 577      * Compares this object against the specified object.
 578      * The result is {@code true} if and only if the argument is
 579      * not {@code null} and it represents the same NetworkInterface
 580      * as this object.
 581      * <p>
 582      * Two instances of {@code NetworkInterface} represent the same
 583      * NetworkInterface if both name and addrs are the same for both.
 584      *
 585      * @param   obj   the object to compare against.
 586      * @return  {@code true} if the objects are the same;
 587      *          {@code false} otherwise.
 588      * @see     java.net.InetAddress#getAddress()
 589      */
 590     public boolean equals(Object obj) {
 591         if (!(obj instanceof NetworkInterface)) {
 592             return false;
 593         }
 594         NetworkInterface that = (NetworkInterface)obj;
 595         if (this.name != null ) {
 596             if (!this.name.equals(that.name)) {
 597                 return false;
 598             }
 599         } else {
 600             if (that.name != null) {
 601                 return false;
 602             }
 603         }
 604 
 605         if (this.addrs == null) {
 606             return that.addrs == null;
 607         } else if (that.addrs == null) {
 608             return false;
 609         }
 610 
 611         /* Both addrs not null. Compare number of addresses */
 612 
 613         if (this.addrs.length != that.addrs.length) {
 614             return false;
 615         }
 616 
 617         InetAddress[] thatAddrs = that.addrs;
 618         int count = thatAddrs.length;
 619 
 620         for (int i=0; i<count; i++) {
 621             boolean found = false;
 622             for (int j=0; j<count; j++) {
 623                 if (addrs[i].equals(thatAddrs[j])) {
 624                     found = true;
 625                     break;
 626                 }
 627             }
 628             if (!found) {
 629                 return false;
 630             }
 631         }
 632         return true;
 633     }
 634 
 635     public int hashCode() {
 636         return name == null? 0: name.hashCode();
 637     }
 638 
 639     public String toString() {
 640         String result = "name:";
 641         result += name == null? "null": name;
 642         if (displayName != null) {
 643             result += " (" + displayName + ")";
 644         }
 645         return result;
 646     }
 647 
 648     private static native void init();
 649 
 650     /**
 651      * Returns the default network interface of this system
 652      *
 653      * @return the default interface
 654      */
 655     static NetworkInterface getDefault() {
 656         return defaultInterface;
 657     }
 658 }