簡體   English   中英

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

  }
}

我遇到此錯誤消息

線程“ AWT-EventQueue-0”中的異常java.lang.NullPointerException

之所以出現此錯誤,是因為您嘗試在null引用上調用method。 您需要先初始化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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM