我想得到安卓手机的IP地址,为此我尝试了InetAddress,但我在Emulator上得到了IP地址127.0.0.1。如何获取实际的IP地址?其次,我想从网络服务器上使用该IP地址联系那个android手机,询问一些信息,比如它的位置。例如:假设phone1需要Phone2的信息,然后Phone1联系with服务器,with服务器使用其保存的ip地址联系phone2,然后phone2将其位置响应给with服务器,with服务器响应Phone1。
发布于 2014-04-02 20:44:46
下面是获取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;
}发布于 2012-06-06 17:07:04
与其让服务器询问手机的位置,不如试着用另一种方式思考。
创建一个应用程序,它将在手机上运行,并定期将其位置发送到您的服务器。然后,当电话2想知道电话1的位置时,它将从服务器获得最新的已知位置。
发布于 2012-06-06 17:20:48
点击此处: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,则没有可用的连接。如果该方法返回一个字符串,则此字符串包含设备当前使用的ip地址,独立于3G或WiFi。
https://stackoverflow.com/questions/10911063
复制相似问题