InetAddress ipAddr;
我在这里尝试做的是我需要获取IP地址然后将其放入套接字
public class L implements ActionListener{
public void actionPerformed(final ActionEvent e){
try {
s = new Socket(ipAddr.getHostAddress(), 6111);
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
dout.writeUTF("L");
dout.writeUTF(" ");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
我有这个错误消息
线程中的异常" AWT-EventQueue-0"显示java.lang.NullPointerException
答案 0 :(得分:0)
您收到此错误是因为您尝试在空引用上调用方法。在使用它来调用本答案后面描述的方法之前,您需要初始化ipAddr
。
s = new Socket(ipAddr.getHostAddress(), 6111); // your code doesn't initialise ipAddr.
目前,您的问题还不清楚您想要哪个IPAddress。所以,我假设您正在寻找系统的环回地址(默认)。初始化InetAddress有几个选项,如下所示:
String url = "localhost";
byte addr[] = {127, 0, 0, 1}; // loopback address
InetAddress ip1 = InetAddress.getByName(url);
InetAddress ip2 = InetAddress.getByAddress(addr);
InetAddress ip3 = InetAddress.getLocalHost();
// proceed with your sample code by using any of these InetAddress references