private String getLocalIPAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterface(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElements();
if ( !inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
// 这里增加限定条件inetAddress instanceof Inet4Address主要是在Android4.0高版本中可能优先得到的是IPV6地址
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e("getIP", ex.toString());
ex.printStackTrace();
}
return null;
}