TCP服务器与IP地址

3
我正在使用以下代码获取我的安卓手机的IP地址。
try {
         for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
             NetworkInterface intf = en.nextElement();
             for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                 InetAddress inetAddress = enumIpAddr.nextElement();
                 if (!inetAddress.isLoopbackAddress()) {
                     return inetAddress.getHostAddress().toString();
                     //return inetAddress;
                 }
             }
         }
     } catch (SocketException ex) {
         Log.e("SALMAN", ex.toString());
     }

它返回的是fe80::94ae:97c:2680:c6cb%rmnet0

然后我在8080端口上设置了一个服务器。

我如何使用此地址连接客户端?我原本期望得到一个IPv4地址...我能通过Chrome或其他方式连接它以测试连接吗?

1个回答

2

使用以下任意一种方式:

WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();

或者:

try {
Socket socket = new Socket("www.stackoverflow.com", 80);
   Log.i("", socket.getLocalAddress().toString());
} catch (Exception e) {
   Log.i("", e.getMessage());
}

您无法通过 Chrome 测试连接,但如果使用 HTTP 协议,则可以通过它进行连接。编写一个带有另一个套接字通信的 Java SE 桌面应用程序。代码非常相似。


谢谢。明确一下,第二种方法可以在4G上工作对吗? - greekygyro
第二个通过您的活动连接工作,这可以是以太网,WiFi或移动连接。第一个仅适用于WiFi。 - paulgavrikov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接