有没有简单的方法时,通过移动数据网络连接到互联网,让我的电话的IP地址。 为了获得无线IP地址我用下面这个简单的技术。
WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
是否有类似于上述的任何方式来获得移动数据网络的IP地址。
我用下面的代码,但它返回的MAC地址,WiFi和蜂窝网络的IP地址,但我感兴趣的只是在蜂窝IP地址。
String ipAddress = null;
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
ipAddress = inetAddress.getHostAddress().toString();
Log.i("Sarao5",ipAddress);
}
}
}
} catch (SocketException ex) {}
使用下面的代码,我在我的应用程序中使用 -
public static String getDeviceIPAddress(boolean useIPv4) {
try {
List<NetworkInterface> networkInterfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface networkInterface : networkInterfaces) {
List<InetAddress> inetAddresses = Collections.list(networkInterface.getInetAddresses());
for (InetAddress inetAddress : inetAddresses) {
if (!inetAddress.isLoopbackAddress()) {
String sAddr = inetAddress.getHostAddress().toUpperCase();
boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
if (useIPv4) {
if (isIPv4)
return sAddr;
} else {
if (!isIPv4) {
// drop ip6 port suffix
int delim = sAddr.indexOf('%');
return delim < 0 ? sAddr : sAddr.substring(0, delim);
}
}
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return "";
}
这是最好的,简单的方法。
希望我的回答是有帮助的。
应避免使用Formatter.formatIPAddress
,用于获取IP地址下面,从你的代码的细微差别; 其返回如果启用其他您需要的蜂窝无线网络一个IP一个功能,你可以修改它ACC需要;
public static String getLocalIpAddress() {
WifiManager wifiMgr = (WifiManager) ApplicationController.getInstance().getSystemService(context.WIFI_SERVICE);
if(wifiMgr.isWifiEnabled()) {
WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
int ip = wifiInfo.getIpAddress();
String wifiIpAddress = String.format("%d.%d.%d.%d",
(ip & 0xff),
(ip >> 8 & 0xff),
(ip >> 16 & 0xff),
(ip >> 24 & 0xff));
return wifiIpAddress;
}
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
Log.i("","111 inetAddress.getHostAddress(): "+inetAddress.getHostAddress());
//the condition after && is missing in your snippet, checking instance of inetAddress
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
Log.i("","111 return inetAddress.getHostAddress(): "+inetAddress.getHostAddress());
return inetAddress.getHostAddress();
}
}
}
return null;
}