/*查看可用的网络接口并选择第一个“正派”的IPv4地址。 *由于模拟器默认使用10.0.2.15,所以只有在没有更好的可用的情况下才使用它。 */
public String getMyIp() {
Set eligible = eligibleIpAddresses();
/* For the emulator, prefer an IP address other than 10.0.2.15 (default emulator address)
* but use it if it is the only one. */
if (eligible.size() > 1) {
eligible.remove("10.0.2.15");
return eligible.iterator().next();
} else if (eligible.size() == 1) {
return eligible.iterator().next();
} else {
Log.w("Using local IP address, no external objects will be discovered","---");
return "127.0.0.1";
}
}
public static Set eligibleIpAddresses() {
Set eligible = new HashSet();
try {
Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces();
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = netInterfaces.nextElement();
Enumeration address = ni.getInetAddresses();
while (address.hasMoreElements()) {
InetAddress addr = address.nextElement();
if (!addr.isLoopbackAddress() && !(addr.getHostAddress().indexOf(":") > -1)) {
eligible.add(addr.getHostAddress());
}
}
}
} catch (Exception e) {
}
return eligible;
}