【问题标题】:How I can use Socket method?如何使用 Socket 方法?
【发布时间】:2014-03-04 13:15:43
【问题描述】:

我是 Android 编程的初学者。我想用这个方法:

Socket socket;
socket.getInetAddress() ;

我想在TextView 中打印我连接的 IP 地址。 这可能吗?我该怎么做?

谢谢!

我试过了,但没有任何效果

 public void onClick(View v) {

  Socket s = new Socket();
  String host ="10.10.20.xxxx";

try {
    s.connect( new InetSocketAddress( host, 6000 ), 1000 );

    InetAddress inetAddress = s.getLocalAddress();
    String ip = inetAddress.getHostAddress();
    //Now, I would like to have printed out the IP-address
    Toast.makeText(getBaseContext(), ip , Toast.LENGTH_SHORT).show();
//But nothing happens
} catch (IOException e) {
    e.printStackTrace();
    }
}
}

【问题讨论】:

  • 你能告诉我们你已经尝试过什么吗?
  • 感谢 Philippe,您的编辑,我更新了我的问题。
  • 你能正常显示Toast 消息吗?
  • 总是先尝试最简单的,然后再以结果为基础。例如,首先尝试打印“Hello!”在Toast。如果可行,则继续使用Socket 的东西。我在下面给出了答案,但我很困惑你为什么要这样做,因为看起来你已经知道你要连接的服务器的地址。 (String host = ....)。

标签: android sockets methods textview ip-address


【解决方案1】:

要获取套接字连接的主机地址,您应该使用getInetAddress() 而不是getLocalAddress()。因此,您的代码可能如下所示:

public void onClick(View v) {

    Socket s = new Socket();
    String host ="10.10.20.xxxx";

    try {
        s.connect( new InetSocketAddress( host, 6000 ), 1000 );

        InetAddress inetAddress = s.getInetAddress();        // <---- Here!
        String ip = inetAddress.getHostAddress();

        Toast.makeText(getBaseContext(), ip , Toast.LENGTH_SHORT).show();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

【讨论】:

  • 现在试试这个解决方案,谢谢!
  • 您可能会遇到异常并且没有看到它(因为try...catch)。尝试将Toast.makeText(getBaseContext(), "ERROR", Toast.LENGTH_SHORT).show(); 添加到catch 以帮助您进行调试。
猜你喜欢
  • 2013-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-27
  • 1970-01-01
  • 1970-01-01
  • 2018-07-28
相关资源
最近更新 更多