我正在研究为本地计算机获取本地tcp / ip配置的类。但是,在声明byte [] mac时。我得到一个nullpointerexecption。所以我正在访问具有空值的东西。但我看不出问题是什么。我想知道是否与我在两种不同方法中使用networkinterface类有关。 错误:
java.lang.NullPointerException
at jlanscan.LocalHost.getMacAddress(LocalHost.java:67)
班
package jlanscan;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* class to Get LocalHost TCP configuration: ip, subnet, router
* @author jorge
*/
public class LocalHost {
InetAddress localhost = null;
String ipV6;
String ipV4;
String hostname;
String iFace;
String macAddr;
Enumeration<NetworkInterface> nets = null;
public LocalHost() throws UnknownHostException, SocketException {
hostname = "localhost";
nets = NetworkInterface.getNetworkInterfaces();
Collections.list(nets).forEach((netint) -> {
try {
if(!netint.isLoopback()) {
displayInterfaceInformation(netint);
}
} catch (SocketException ex) {
Logger.getLogger(LocalHost.class.getName()).log(Level.SEVERE, null, ex);
}
try {
getMacAddress();
} catch (SocketException ex) {
Logger.getLogger(LocalHost.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnknownHostException ex) {
Logger.getLogger(LocalHost.class.getName()).log(Level.SEVERE, null, ex);
}
});
}
public void displayInterfaceInformation(NetworkInterface netint) {
Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
for (InetAddress inetAddress : Collections.list(inetAddresses)) {
if(inetAddress.getHostAddress().contains("%")) {
String[] iface = inetAddress.getHostAddress().split("%");
ipV6 = iface[0];
iFace = iface[1];
}
ipV4 = inetAddress.getHostAddress();
// System.out.println(inetAddress.getHostAddress());
}
}
public void getMacAddress() throws SocketException, UnknownHostException {
localhost = InetAddress.getLocalHost();
NetworkInterface ni = NetworkInterface.getByInetAddress(localhost);
byte[] mac = ni.getHardwareAddress();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
macAddr = sb.toString();
}
public InetAddress getLocalhost() {
return localhost;
}
public String getIpAddressV4() {
return ipV4;
}
public String getHostname() {
return hostname;
}
@Override
public String toString() {
return "Localhost: interface: " + iFace +" ipV4: " + ipV4 +" ipV6: "+ ipV6 +" hostname: "+ hostname +" mac: "+macAddr;
}
}