簡體   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