2015-01-13 169 views
0

當試圖通過WiFi管理器獲取路由器IP地址無法檢索相同。以下是代碼片段。dhcp.ipAddress返回0

WifiManager wifiMgr = (WifiManager)context.getSystemService(Context.WIFI_SERVICE); 
DhcpInfo dhcp = wifiMgr.getDhcpInfo(); 
System.out.println("ip add - " + dhcp.ipAddress + "gateway add -" + dhcp.gateway); 

IP add和gateway add都一直返回0。 我哪裏錯了?還有什麼需要做的嗎?

我已經經歷了許多相關的堆棧溢出問題,但沒有答案。 請仔細回答這個問題,如果您需要任何進一步的信息,您的親切快速回復將非常有幫助,請告訴我。

+0

您是否在獲取dhcp信息之前檢查Wifi網絡是否可用?當wifi被禁用dhcp信息返回0. –

+0

嗨,Alvaro你是對的,我沒有檢查過。其實這個問題與某個時間問題有關。我使用wifiMgr.enableNetwrok()啓用網絡,但在此之後,我不等待操作完成,在此之前我只能檢索dhcp信息。現在添加延遲,它正在工作。 –

+0

現在我得到的IP地址,但將其轉換爲點狀格式時,它是反向IP我得到,任何想法如何照顧endian問題,同時整數IP轉換爲字符串IP? –

回答

0

如果發生RemoteException,它將返回null。也許你在清單文件中缺少Internet權限?

+0

它不返回null,它返回0 –

0

你應該檢查是否有wifi網絡可用第一,如果沒有,DhcpInfo.ipAdress返回0

如果你想轉換爲虛格式,試試這個(如果它是一個有效的IPv4地址):

try { 
    WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE); 
    int ipAddress = wm.getDhcpInfo().ipAddress; 
    byte[] ipAddressbyte = BigInteger.valueOf(ipAddress).toByteArray(); 
    for (int i = 0; i < ipAddressbyte.length/2; i++) { 
     int temp = ipAddressbyte[i]; 
     ipAddressbyte[i] = ipAddressbyte[ipAddressbyte.length - i - 1]; 
     ipAddressbyte[ipAddressbyte.length - i - 1] = (byte) temp; 
    } 

    InetAddress myaddr = InetAddress.getByAddress(ipAddressbyte); 
    String hostaddr = myaddr.getHostAddress(); // numeric representation (such as "127.0.0.1") 
    Log.d("INET",hostaddr); 
} 
catch (Exception exc) { 
    Log.d("Exception", exc.getMessage()); 
} 
+0

但是,這總是假設小端格式。 –