问题描述
- Android通过获取IP的代码获取到的IP不对
-
下面是获取IP的代码:
public String getLocalIpAddress() {try {
for (Enumeration en = NetworkInterface
.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration enumIpAddr = intf
.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()&& !inetAddress.isLinkLocalAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e("WifiPreference IpAddress", ex.toString());
}
return null;
}
我在我的小米手机上用这个方法获取本机的IP地址,获取到的IP是10.0.2.15,可是我在设置里找到本机的IP地址是10.88.134.210,这是为什么啊,还有我连上wifi后的ip地址应该是10.225.134.22,但是通过这个方法获取到的IP地址还是10.0.2.15,求大神指点迷津!!!!!!
解决方案
//必写
//必写
// 获取本地IP
public static String test() {
try {
for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = (NetworkInterface) en.nextElement();
for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e("WifiPreference IpAddress", ex.toString());
}
return null;
}
private void initView() {
this.findViewById(R.id.btnInsert).setOnClickListener(this);
this.findViewById(R.id.btnDel).setOnClickListener(this);
this.findViewById(R.id.btnUpdate).setOnClickListener(this);
this.findViewById(R.id.btnQuery).setOnClickListener(this);
if (isBase) {
mDataManager = DataManager.getInstance(this);
}
}
4.2.1手机工作ok
解决方案二:
请参考网站。。 http://blog.sina.com.cn/s/blog_77c632410101cy1v.html
解决方案三:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
// 获取本地IP
public static String test() {
try {
for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = (NetworkInterface) en.nextElement();
for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e("WifiPreference IpAddress", ex.toString());
}
return null;
}