2012-06-06 44 views
1

我想获取Android手机的IP地址,为此我尝试了InetAddress,但是我在仿真器上获得了IP地址127.0.0.1。我怎样才能得到实际的IP地址。 其次,我想通过使用Web服务器的IP地址联系该android移动设备,询问其位置等信息。 对于例如:假设Phone1需要Phone2的信息,则Phone1使用其保存的IP地址联系web服务器和web服务器联系人phone2,然后phone2响应其位置给web服务器和web服务器响应phone1。我想获取Android手机的IP地址,以及如何从Web服务器联系android手机使用该IP地址获取一些信息?

回答

0

此代码为越来越IPV4:

private String getLocalIpAddress() { 
     try { 
      for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { 
       NetworkInterface intf = en.nextElement(); 
       for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { 
        InetAddress in`enter code here`etAddress = enumIpAddr.nextElement(); 
        if (!inetAddress.isLoopbackAddress()) { 
         if (inetAddress instanceof Inet4Address) { 
          return ((Inet4Address)inetAddress).getHostAddress().toString(); 
         } 
        } 
       } 
      } 
     } catch (SocketException ex) { 
      Log.e("ServerActivity", ex.toString()); 
     } 
     return null; 
    } 
+0

此代码获取IPV4 – Narendra

0

与其让服务器询问手机的位置,不如尝试另一种方式。

创建一个将在手机上运行的应用程序,并定期将其位置发送到您的服务器。然后,当电话2想知道电话1的位置时,它将从服务器获得最新的已知位置。

+0

这将填补我的数据库与纬度郎,我只想设备的IP地址是更新时,它的变化,我想异步调用时请求来自phone1,那么只有phone2必须与位置联系。 – KJS

+0

不一定会填满您的数据库,因为您不必存储每个位置,只能存储最近的位置。 – sschrass

+0

谢谢但我试图以不同的方式实现它 – KJS

0

这里找到:http://www.droidnova.com/get-the-ip-address-of-your-device,304.html

public String getLocalIpAddress() { 
try { 
    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { 
     NetworkInterface intf = en.nextElement(); 
     for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { 
      InetAddress inetAddress = enumIpAddr.nextElement(); 
      if (!inetAddress.isLoopbackAddress()) { 
       return inetAddress.getHostAddress().toString(); 
      } 
     } 
    } 
} catch (SocketException ex) { 
    Log.e(LOG_TAG, ex.toString()); 
} 
return null; 
} 

因此,如果此方法返回null,没有可用的连接。 如果该方法返回一个字符串,则该字符串包含独立于3G或WiFi的设备当前使用的IP地址。

+0

我已经使用这个代码,它也给我在仿真器上的IP地址10.0.2.15,当它将在实际设备上运行时它会给出正确的IP地址。 – KJS

+0

我这么认为,是的。注意NAT(路由器等)。 – sschrass

+0

和我怎样才能访问信息从Android手机使用该IP地址 – KJS