1 import static java
.lang
.System
.out
;
3 import java
.net
.InetAddress
;
4 import java
.net
.NetworkInterface
;
5 import java
.net
.SocketException
;
6 import java
.util
.Collections
;
7 import java
.util
.Enumeration
;
9 // this utility displays information on addresses and ports, you don't need to use it
10 public class NetHelper
12 public static void main(String args
[]) throws SocketException
{
13 Enumeration
<NetworkInterface
> nets
= NetworkInterface
.getNetworkInterfaces();
15 for (NetworkInterface netIf
: Collections
.list(nets
)) {
16 out
.printf("Display name: %s\n", netIf
.getDisplayName());
17 out
.printf("Name: %s\n", netIf
.getName());
18 displayInterfaceInformation(netIf
);
19 displaySubInterfaces(netIf
);
24 public static NetworkInterface
getNetworkInterface(String netName
) {
25 NetworkInterface netIntf
= null;
27 for (Enumeration
<NetworkInterface
> en
= NetworkInterface
28 .getNetworkInterfaces(); en
.hasMoreElements();) {
29 NetworkInterface intf
= en
.nextElement();
30 if (intf
.getName().compareToIgnoreCase(netName
) == 0) {
35 } catch (SocketException e
) {
37 .println("Socket Exception failed to find internet addresses!");
44 public static InetAddress
getFirstNonLocalHost(NetworkInterface netIntf
) {
45 Enumeration
<InetAddress
> hosts
= netIntf
.getInetAddresses();
46 InetAddress address
= null;
47 while (hosts
.hasMoreElements()) {
48 InetAddress host
= hosts
.nextElement();
49 if (!host
.isLinkLocalAddress() && !host
.isLoopbackAddress()) {
59 static String
getMac(NetworkInterface netint
) throws SocketException
{
60 byte[] mac
= netint
.getHardwareAddress();
63 StringBuilder sb
= new StringBuilder();
64 for (int i
= 0; i
< mac
.length
; i
++) {
65 sb
.append(String
.format("%02X%s", mac
[i
], (i
< mac
.length
- 1) ?
"-" : ""));
70 //System.out.println(sb.toString());
73 static void displayInterfaceInformation(NetworkInterface netint
) throws SocketException
{
74 out
.printf("Display name: %s\n", netint
.getDisplayName());
75 out
.printf("Name: %s\n", netint
.getName());
76 out
.printf("MAC: %s\n", getMac(netint
));
77 Enumeration
<InetAddress
> inetAddresses
= netint
.getInetAddresses();
78 for (InetAddress inetAddress
: Collections
.list(inetAddresses
)) {
79 out
.printf("InetAddress: %s\n", inetAddress
);
80 out
.println("LOCAL:" + Boolean
.toString(inetAddress
.isLoopbackAddress() || inetAddress
.isLinkLocalAddress()));
85 static void displaySubInterfaces(NetworkInterface netIf
) throws SocketException
{
86 Enumeration
<NetworkInterface
> subIfs
= netIf
.getSubInterfaces();
88 for (NetworkInterface subIf
: Collections
.list(subIfs
)) {
89 out
.printf("\tSub Interface Display name: %s\n", subIf
.getDisplayName());
90 out
.printf("\tSub Interface Name: %s\n", subIf
.getName());
91 displayInterfaceInformation(subIf
);