[英]Getting the IP address of the android device when connected to 3G mobile network
[英]getting mobile network ip address
您好,我正在使用此方法獲取移動網絡 IP 地址
public static String getMobileIPAddress() {
try {
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces) {
List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
for (InetAddress addr : addrs) {
if (!addr.isLoopbackAddress()) {
return addr.getHostAddress();
}
}
}
} catch (Exception ex) { } // for now eat exceptions
return "";
}
但返回值似乎不是 IP:fe80::dc19:94ff:fe6f:ae7b%dummy0
其實你的代碼是正確的。 它正在獲取InetAddresses
列表,其中ip 地址也存在mac 地址。 您必須使用InetAddressUtils.isIPv4Address
或addr instanceof Inet4Address
( API >= 23 ) 來過濾其中的IP 地址。 檢查以下:
public static String getMobileIPAddress() {
try {
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces) {
List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
for (InetAddress addr : addrs) {
if (!addr.isLoopbackAddress() &&
addr instanceof Inet4Address) {
return addr.getHostAddress();
}
}
}
} catch (Exception ex) { } // for now eat exceptions
return "";
}
此代碼獲取WIFI IP地址:
WifiManager wm = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.