2015-01-13 171 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

但是,这总是假设小端格式。 –