【问题标题】:Getting ip address and putting it to socket -java获取IP地址并将其放入socket -java
【发布时间】:2018-08-10 17:32:42
【问题描述】:
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】:

    您收到此错误是因为您尝试在空引用上调用方法。您需要先初始化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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-02
      • 2010-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-04
      • 2011-12-26
      相关资源
      最近更新 更多