繁体   English   中英

如何从设备获取默认IP地址?

[英]How to get default ip address from device?

我需要知道,因为当我发送广播数据包时,我无法检查它是否来自我自己。 我的代码问题是Android,它在台式机上运行良好。 对于android来说,它一直给我一个IPV6,但是它给我的广播地址是正常的...

此函数将返回主机的IP地址。

private String getHostIpAddress() throws SocketException {
    Enumeration<NetworkInterface> interfaces;
    interfaces = NetworkInterface.getNetworkInterfaces();
    while (interfaces.hasMoreElements()) {
        NetworkInterface current = interfaces.nextElement();
        if (!current.isUp() || current.isLoopback() || current.isVirtual())
            continue;
        Enumeration<InetAddress> addresses = current.getInetAddresses();
        while (addresses.hasMoreElements()) {
            InetAddress currentAddr = addresses.nextElement();
            if (currentAddr.isSiteLocalAddress()) 
                return currentAddr.getHostAddress();                
        }
    }
    return null;
}

您可以使用以下代码获取设备的IP地址:

WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM