我怎么用Socket方法?

时间:2014-03-04 13:15:43

标签: android sockets methods textview ip-address

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

1 个答案:

答案 0 :(得分:0)

要获取套接字所连接的主机的地址,您应使用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();
    }
}