获取 ip 地址并将其放入套接字 -java

Getting ip address and putting it to socket -java

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();  
      }

  }
}

我收到这条错误消息

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException

您收到此错误是因为您试图在空引用上调用方法。您需要先初始化 ipAddr,然后再使用它来调用本答案稍后描述的方法。

s = new Socket(ipAddr.getHostAddress(), 6111);   // your code doesn't initialise ipAddr.

目前,从你的问题中不清楚你想要哪个IP地址。因此,我假设您正在寻找系统的环回地址(默认)。初始化 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