-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetworkInfo.java
More file actions
57 lines (54 loc) · 2.12 KB
/
NetworkInfo.java
File metadata and controls
57 lines (54 loc) · 2.12 KB
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
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.net.UnknownHostException;
public class NetworkInfo
{
public void showNICDetails()
{
try
{
//Gets local host information
InetAddress localhost = InetAddress.getLocalHost();
System.out.println("Local Hostname: " + localhost.getHostName());
System.out.println("Local IP Address: " + localhost.getHostAddress());
//Gets information about network interfaces
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements())
{
NetworkInterface networkInterface = networkInterfaces.nextElement();
System.out.println("Interface Name: " + networkInterface.getDisplayName());
if (networkInterface.getHardwareAddress() != null)
{
System.out.println("Interface Hardware Address: " + formatMACAddress(networkInterface.getHardwareAddress()));
}
Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
while (inetAddresses.hasMoreElements())
{
InetAddress inetAddress = inetAddresses.nextElement();
System.out.println("IP Address: " + inetAddress.getHostAddress());
}
System.out.println();
}
}
catch (SocketException | UnknownHostException e)
{
e.printStackTrace();
}
}
//Helper method to format the MAC address as a string
private static String formatMACAddress(byte[] mac)
{
StringBuilder formattedMAC = new StringBuilder();
for (byte b : mac)
{
formattedMAC.append(String.format("%02X:", b));
}
if (formattedMAC.length() > 0)
{
formattedMAC.deleteCharAt(formattedMAC.length() - 1); //Remove the trailing ':'
}
return formattedMAC.toString();
}
}