-
Notifications
You must be signed in to change notification settings - Fork 668
/
NetworkInterface.java
702 lines (614 loc) · 26 KB
/
NetworkInterface.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
/*
* Copyright (c) 2000, 2017, 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.
*/
package java.net;
import java.security.AccessController;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
/**
* 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
*/
// NetworkInterface表示一个网络接口,这可以是一个物理的网络接口,也可以是一个虚拟的网络接口
public final class NetworkInterface {
private static final NetworkInterface defaultInterface; // 当前系统的默认网络接口
private static final int defaultIndex; // 默认网络接口的索引
private String name; // 当前网络接口名称(机器名称,如lo、et0、et1、wlan1)
private String displayName; // 当前网络接口名称(别名,如Software Loopback Interface、VMware Virtual Ethernet Adapter)
private int index; // 当前网络接口的索引
private InetAddress[] addrs; // 绑定到当前网络接口的网络IP(包含IP4和IP6地址)
private InterfaceAddress[] bindings; // 当前网络接口绑定的IP,包括网络IP和广播IP
private NetworkInterface[] childs; // 当前网络接口的子网络接口(如虚拟接口)
private NetworkInterface parent = null; // 当前子网络接口的父网络接口(如物理接口)
private boolean virtual = false; // 当前网络接口是否为虚拟化接口
static {
AccessController.doPrivileged(new java.security.PrivilegedAction<>() {
public Void run() {
System.loadLibrary("net");
return null;
}
});
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(String name, int index, InetAddress[] addrs) {
this.name = name;
this.index = index;
this.addrs = addrs;
}
/*▲ 构造器 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 工厂方法 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* 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}.
*/
// 搜索具有指定名称的网络接口
public static NetworkInterface getByName(String name) throws SocketException {
if(name == null) {
throw new NullPointerException();
}
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
*/
// 搜索指定索引处的网络接口
public static NetworkInterface getByIndex(int index) throws SocketException {
if(index<0) {
throw new IllegalArgumentException("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.
*
* 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}.
*/
// 搜索绑定到指定IP的网络接口
public static NetworkInterface getByInetAddress(InetAddress addr) throws SocketException {
if(addr == null) {
throw new NullPointerException();
}
if(!(addr instanceof Inet4Address || addr instanceof Inet6Address)) {
throw new IllegalArgumentException("invalid address type");
}
return getByInetAddress0(addr);
}
/**
* Returns an {@code Enumeration} of 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.
*
* @return an Enumeration of NetworkInterfaces found on this machine
*
* @throws SocketException if an I/O error occurs,
* or if the platform does not have at least one configured
* network interface.
* @apiNote this method can be used in combination with
* {@link #getInetAddresses()} to obtain all IP addresses for this node
* @see #networkInterfaces()
*/
// 获得本机上所有网络接口,包括物理的和虚拟的
public static Enumeration<NetworkInterface> getNetworkInterfaces() throws SocketException {
NetworkInterface[] netifs = getAll();
if(netifs != null && netifs.length>0) {
// 枚举化
return enumerationFromArray(netifs);
} else {
throw new SocketException("No network interfaces configured");
}
}
/**
* Returns a {@code Stream} of all the interfaces on this machine. The
* {@code Stream} contains at least one interface, possibly representing a
* loopback interface that only supports communication between entities on
* this machine.
*
* @return a Stream of NetworkInterfaces found on this machine
*
* @throws SocketException if an I/O error occurs,
* or if the platform does not have at least one configured
* network interface.
* @apiNote this method can be used in combination with
* {@link #inetAddresses()}} to obtain a stream of all IP addresses for
* this node, for example:
* <pre> {@code
* Stream<InetAddress> addrs = NetworkInterface.networkInterfaces()
* .flatMap(NetworkInterface::inetAddresses);
* }</pre>
* @since 9
*/
// 获得本机上所有网络接口,包括物理的和虚拟的
public static Stream<NetworkInterface> networkInterfaces() throws SocketException {
NetworkInterface[] netifs = getAll();
if(netifs != null && netifs.length>0) {
return streamFromArray(netifs);
} else {
throw new SocketException("No network interfaces configured");
}
}
/*▲ 工厂方法 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 属性 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Get the name of this network interface.
*
* @return the name of this network interface
*/
// 网络接口名称
public String getName() {
return name;
}
/**
* 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.
*/
// 获取网络接口名称(别名,如Software Loopback Interface、VMware Virtual Ethernet Adapter)
public String getDisplayName() {
/* strict TCK conformance */
return "".equals(displayName) ? null : displayName;
}
/**
* 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
*/
// 获取网络接口的索引
public int getIndex() {
return index;
}
/**
* Get 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
*
* @see #inetAddresses()
*/
// 获取绑定到当前网络接口的IP地址(包括IP4和IP6地址)
public Enumeration<InetAddress> getInetAddresses() {
InetAddress[] addrs = getCheckedInetAddresses();
// 枚举化
return enumerationFromArray(addrs);
}
/**
* Get a Stream of 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 Stream. However, if the caller has the
* {@link NetPermission}("getNetworkInformation") permission, then all
* InetAddresses are returned.
*
* @return a Stream object with all or a subset of the InetAddresses
* bound to this network interface
*
* @since 9
*/
// 获取绑定到当前网络接口的IP地址(包括IP4和IP6地址)
public Stream<InetAddress> inetAddresses() {
InetAddress[] addrs = getCheckedInetAddresses();
// 流化
return streamFromArray(addrs);
}
/**
* 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
*/
// 获取网络接口绑定的IP(包括网络IP和广播IP)
public List<InterfaceAddress> getInterfaceAddresses() {
List<InterfaceAddress> lst = new ArrayList<>(1);
if(bindings != null) {
SecurityManager sec = System.getSecurityManager();
for(InterfaceAddress binding : bindings) {
try {
if(sec != null) {
sec.checkConnect(binding.getAddress().getHostAddress(), -1);
}
lst.add(binding);
} 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
*
* @see #subInterfaces()
* @since 1.6
*/
// 获取当前网络接口的子网络接口(如虚拟接口)
public Enumeration<NetworkInterface> getSubInterfaces() {
return enumerationFromArray(childs);
}
/**
* Get a Stream of all subinterfaces (also known as virtual
* interfaces) attached to this network interface.
*
* @return a Stream object with all of the subinterfaces
* of this network interface
*
* @since 9
*/
// 获取绑定到当前网络接口的子网络接口(如虚拟接口)
public Stream<NetworkInterface> subInterfaces() {
return streamFromArray(childs);
}
/**
* 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
*/
// 获取当前子网络接口的父网络接口(如物理接口)
public NetworkInterface getParent() {
return parent;
}
/**
* 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")
*
* @throws SocketException if an I/O error occurs.
* @since 1.6
*/
// 获取当前网络接口的硬件地址,通常是MAC地址
public byte[] getHardwareAddress() throws SocketException {
SecurityManager sec = System.getSecurityManager();
if(sec != null) {
try {
sec.checkPermission(new NetPermission("getNetworkInformation"));
} catch(SecurityException e) {
if(!getInetAddresses().hasMoreElements()) {
// don't have connect permission to any local address
return null;
}
}
}
// 遍历绑定到当前网络接口的网络地址(IP4和IP6地址)
for(InetAddress addr : addrs) {
// 选择IP4地址
if(addr instanceof Inet4Address) {
// 获取MAC地址
return getMacAddr0(addr.getAddress(), name, index);
}
}
return getMacAddr0(null, name, index);
}
/**
* Returns the default network interface of this system
*
* @return the default interface
*/
// 获取当前系统的默认网络接口
static NetworkInterface getDefault() {
return defaultInterface;
}
/*▲ 属性 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 信息 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns whether a network interface is up and running.
*
* @return {@code true} if the interface is up and running.
*
* @throws SocketException if an I/O error occurs.
* @since 1.6
*/
// 判断网络接口是否已启动并正在运行
public boolean isUp() throws SocketException {
return isUp0(name, index);
}
/**
* Returns whether a network interface is a loopback interface.
*
* @return {@code true} if the interface is a loopback interface.
*
* @throws SocketException if an I/O error occurs.
* @since 1.6
*/
// 判断当前网络接口是否为本地环回接口
public boolean isLoopback() throws SocketException {
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.
*
* @throws SocketException if an I/O error occurs.
* @since 1.6
*/
// 判断当前接口是否为点对点接口
public boolean isPointToPoint() throws SocketException {
return isP2P0(name, index);
}
/**
* 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.
*
* @return {@code true} if this interface is a virtual interface.
*
* @since 1.6
*/
// 判断当前网络接口是否为虚拟接口
public boolean isVirtual() {
return virtual;
}
/**
* Returns whether a network interface supports multicasting or not.
*
* @return {@code true} if the interface supports Multicasting.
*
* @throws SocketException if an I/O error occurs.
* @since 1.6
*/
// 判断当前网络接口是否支持组播
public boolean supportsMulticast() throws SocketException {
return supportsMulticast0(name, index);
}
/**
* Returns the Maximum Transmission Unit (MTU) of this interface.
*
* @return the value of the MTU for that interface.
*
* @throws SocketException if an I/O error occurs.
* @since 1.6
*/
// 获取当前网络接口的最大传输单元(MTU)
public int getMTU() throws SocketException {
return getMTU0(name, index);
}
/*▲ 信息 ████████████████████████████████████████████████████████████████████████████████┛ */
// 将给定的数组包装到枚举器中
private static <T> Enumeration<T> enumerationFromArray(T[] a) {
return new Enumeration<>() {
int i = 0;
@Override
public T nextElement() {
if(i<a.length) {
return a[i++];
} else {
throw new NoSuchElementException();
}
}
@Override
public boolean hasMoreElements() {
return i<a.length;
}
};
}
// 将给定的数组包装到Stream中
private static <T> Stream<T> streamFromArray(T[] a) {
return StreamSupport.stream(Spliterators.spliterator(a, Spliterator.DISTINCT | Spliterator.IMMUTABLE | Spliterator.NONNULL), false);
}
// 获取绑定到当前网络接口的网络地址(IP4和IP6地址)
private InetAddress[] getCheckedInetAddresses() {
InetAddress[] local_addrs = new InetAddress[addrs.length];
boolean trusted = true;
SecurityManager sec = System.getSecurityManager();
if(sec != null) {
try {
sec.checkPermission(new NetPermission("getNetworkInformation"));
} catch(SecurityException e) {
trusted = false;
}
}
int i = 0;
for(InetAddress addr : addrs) {
try {
if(!trusted) {
sec.checkConnect(addr.getHostAddress(), -1);
}
local_addrs[i++] = addr;
} catch(SecurityException e) {
}
}
return Arrays.copyOf(local_addrs, i);
}
private static native NetworkInterface[] getAll() throws SocketException;
private static native NetworkInterface getByName0(String name) throws SocketException;
private static native NetworkInterface getByIndex0(int index) throws SocketException;
private static native NetworkInterface getByInetAddress0(InetAddress addr) throws SocketException;
private static native boolean isUp0(String name, int ind) throws SocketException;
private static native boolean isLoopback0(String name, int ind) throws SocketException;
private static native boolean supportsMulticast0(String name, int ind) throws SocketException;
private static native boolean isP2P0(String name, int ind) throws SocketException;
private static native byte[] getMacAddr0(byte[] inAddr, String name, int ind) throws SocketException;
private static native int getMTU0(String name, int ind) throws SocketException;
private static native void init();
/**
* Compares this object against the specified object.
* The result is {@code true} if and only if the argument is
* not {@code null} and it represents the same NetworkInterface
* as this object.
* <p>
* Two instances of {@code NetworkInterface} represent the same
* NetworkInterface if both name and addrs are the same for both.
*
* @param obj the object to compare against.
*
* @return {@code true} if the objects are the same;
* {@code false} otherwise.
*
* @see java.net.InetAddress#getAddress()
*/
@Override
public boolean equals(Object obj) {
if(!(obj instanceof NetworkInterface)) {
return false;
}
NetworkInterface that = (NetworkInterface) obj;
if(this.name != null) {
if(!this.name.equals(that.name)) {
return false;
}
} else {
if(that.name != null) {
return false;
}
}
if(this.addrs == null) {
return that.addrs == null;
} else if(that.addrs == null) {
return false;
}
/* Both addrs not null. Compare number of addresses */
if(this.addrs.length != that.addrs.length) {
return false;
}
InetAddress[] thatAddrs = that.addrs;
int count = thatAddrs.length;
for(int i = 0; i<count; i++) {
boolean found = false;
for(int j = 0; j<count; j++) {
if(addrs[i].equals(thatAddrs[j])) {
found = true;
break;
}
}
if(!found) {
return false;
}
}
return true;
}
@Override
public int hashCode() {
return name == null ? 0 : name.hashCode();
}
@Override
public String toString() {
String result = "name:";
result += name == null ? "null" : name;
if(displayName != null) {
result += " (" + displayName + ")";
}
return result;
}
}