//获取ip地址
public static String getLocalIPAddress(Context context) {
NetworkInfo info = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info != null && info.isConnected()) {
if (info.getType() == ConnectivityManager.TYPE_MOBILE) { //3G/4G网络
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() && inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException e) {
Log.e(TAG,"获取3G/4G网络IP失败");
}
} else if (info.getType() == ConnectivityManager.TYPE_WIFI) { // wifi
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String ipAddress = int2Sip(wifiInfo.getIpAddress());
return ipAddress;
} else if (info.getType() == ConnectivityManager.TYPE_ETHERNET) { //有线
ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
Network network = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
network = mConnectivityManager.getActiveNetwork();
LinkProperties linkProperties = mConnectivityManager.getLinkProperties(network);
for (LinkAddress linkAddress : linkProperties.getLinkAddresses()) {
InetAddress address = linkAddress.getAddress();
if (address instanceof Inet4Address) {
return address.getHostAddress();
}
}
}
return "0.0.0.0";
}
} else {
return "0.0.0.0";
}
return null;
}
/**
* 将ip的整数形式转换成ip形式
* @param ip
* @return
*/
public static String int2Sip(int ip) {
StringBuilder sb = new StringBuilder();
sb.append(ip & 0xFF).append(".");
sb.append((ip >> 8) & 0xFF).append(".");
sb.append((ip >> 16) & 0xFF).append(".");
sb.append((ip >> 24) & 0xFF);
return sb.toString();
}
android获取有线、wifi、3G(4G)的IP
获取设备IP地址的Java方法
最新推荐文章于 2024-03-25 15:47:00 发布
本文介绍了一种在Android设备上使用Java代码获取不同网络类型(如3G/4G、WiFi、有线)下本地IP地址的方法。通过利用ConnectivityManager、NetworkInterface和WifiManager等API,该方法能适应多种网络环境。
2260

被折叠的 条评论
为什么被折叠?



