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