获取IP地址并将其放入socket -java

问题描述 投票:0回答:1
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

java sockets nullpointerexception network-programming ip-address
1个回答
0
投票

您收到此错误是因为您尝试在空引用上调用方法。在使用ipAddr调用本回答后面描述的方法之前,需要初始化s = new Socket(ipAddr.getHostAddress(), 6111); // your code doesn't initialise ipAddr.

    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

目前,从您的问题中不清楚您想要哪个IPAddress。所以,我假设您正在寻找系统的环回地址(默认)。初始化InetAddress有几个选项,如下所示:

qazxswpoi
© www.soinside.com 2019 - 2024. All rights reserved.