小编Rog*_*ger的帖子

用java的Android IP地址

我正在编写支持多人游戏的Android视频游戏.有一个专用的服务器运行,当通过打开套接字点击多人游戏按钮时,机器人连接到这个服务器(这很好).服务器基本上只是作为配对系统.

当客户端托管游戏时,服务器会将该客户端添加到主机列表中.其他客户端可以选择查看此列表,然后连接到该主机.这就是问题所在.服务器应该跟踪主机的ip /端口,然后其他客户端应该使用此信息与主机打开套接字然后游戏启动.我正在尝试让主机将自己的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();
                }
            }
        }
    } catch (SocketException ex) {
    }
Run Code Online (Sandbox Code Playgroud)

这将返回10.0.2.15,这显然对其他客户端无用.

我试过的另一种方法是:

String hostName = InetAddress.getLocalHost().getHostName();
        InetAddress addrs[] = InetAddress.getAllByName(hostName);
        for (InetAddress addr: addrs) {
            System.out.println ("addr.getHostAddress() = " + addr.getHostAddress());
            System.out.println ("addr.getHostName() = " + addr.getHostName());
            System.out.println ("addr.isAnyLocalAddress() = " + addr.isAnyLocalAddress());
            System.out.println ("addr.isLinkLocalAddress() = " + …
Run Code Online (Sandbox Code Playgroud)

java networking android

2
推荐指数
1
解决办法
7289
查看次数

标签 统计

android ×1

java ×1

networking ×1