Android获取移动设备的IP地址
16lz
2022-04-19
写一个工具类
public class Tools {
public static String getLocalIpAddress() {
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()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e("出错啦", ex.toString());
}
return null;
}
}
然后
WifiManager wm = (WifiManager)getSystemService(WIFI_SERVICE);
WifiInfo wi = wm.getConnectionInfo();
System.out.println("IP地址是:"+Tools.getLocalIpAddress());
System.out.println("SSID:"+wi.getSSID());
最后记得加两个权限
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
public class Tools {
public static String getLocalIpAddress() {
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()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e("出错啦", ex.toString());
}
return null;
}
}
然后
WifiManager wm = (WifiManager)getSystemService(WIFI_SERVICE);
WifiInfo wi = wm.getConnectionInfo();
System.out.println("IP地址是:"+Tools.getLocalIpAddress());
System.out.println("SSID:"+wi.getSSID());
最后记得加两个权限
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
更多相关文章
- Android(安卓)获取音频时长
- android 文件目录权限
- android 6.0权限问题处理的核心代码--shouldShowRequestPermissi
- Android(安卓)studio升级3.0.1之后原项目签名打包出错
- 【原创】android webview 加载网络视频
- android需要的访问权限(不断更新,希望大家多交流)
- Android之简易电话 & 短信
- s5p4418-android5.1.1编译出错问题1
- android 6.0及以上危险权限的获取