2013-01-12 63 views
0

我有一个服务,用于侦听连接,并且我希望它仅在特定网络上侦听。我可以让我的设备的IP地址是这样的:在Android中获取网络IP地址

但该设备的IP,而不是
private void printNetworkInterfaces() 
    { 
     try 
     { 
      Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces(); 
      for (NetworkInterface ni : Collections.list(nis)) 
      { 
       Enumeration<InetAddress> iis = ni.getInetAddresses(); 

       for (InetAddress ia : Collections.list(iis)) 
       { 
        // We only want IPv4 addresses 
        if (!isIPv4(ia.getHostAddress())) 
         continue; 
        // Do tomething with ia.getHostAddress(); 


       } 
      }  
     } 
     catch (SocketException e) 
     { 
      Log.w(TAG,e); 
     } 
    } 

,我想网络的IP听取该网络上。 例如,如果IP是192.168.1.1,那么网络IP应该是192.168.1.0。

我可以用0直接替换第4个值,但是这对其他网络会失败。

有什么方法可以获得与InetAddress.getHostAddress()返回的IP地址关联的网络地址; ?

+0

的可能重复[我怎样才能通过编程方式在同一网络上得到其他WiFi功能的设备的IP地址?(http://stackoverflow.com/questions/12103898/how-can-i-get- ip-addresses-of-other-wifi-enabled-devices-by-programmatically-on) – Sameer

+0

他正在网络上询问其他IP。我正在询问网络本身的IP地址。 – Twinone

回答

1

从网络掩码和IP您可以计算网络IP。

wifii= (WifiManager) getSystemService(Context.WIFI_SERVICE); 
d=wifii.getDhcpInfo(); 
s_dns1="DNS 1: "+String.valueOf(d.dns1); 
s_dns2="DNS 2: "+String.valueOf(d.dns2);  
s_gateway="Default Gateway: "+String.valueOf(d.gateway);  
s_ipAddress="IP Address: "+String.valueOf(d.ipAddress); 
s_leaseDuration="Lease Time: "+String.valueOf(d.leaseDuration);  
s_netmask="Subnet Mask: "+String.valueOf(d.netmask);  
s_serverAddress="Server IP: "+String.valueOf(d.serverAddress); 
+0

我该如何计算?此外,DhcpInfo仅在WifiManager中,不在ConnectivityManager中。 – Twinone

+0

简单地将掩码位与ip位进行比较。 http://en.wikipedia.org/wiki/Subnetwork或使用此:http://stackoverflow.com/questions/1221517/how-to-get-subnet-mask-using-java – Totoo

+0

好吧,谢谢你,这工作。 – Twinone