【发布时间】: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