下面是獲取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