android获取ip
时间: 2023-07-28 08:16:17 浏览: 138
Android获取IP的方法可以通过以下步骤实现:
1. 首先需要在AndroidManifest.xml文件中添加网络权限:
```xml
<uses-permission android:name="android.permission.INTERNET"/>
```
2. 然后在代码中获取IP地址:
```java
public String getIPAddress() {
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.isLinkLocalAddress() && !inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
```
这个方法会遍历所有的网络接口,获取IP地址并返回。需要注意的是,这个方法需要在子线程中执行,否则会抛出NetworkOnMainThreadException异常。
阅读全文
相关推荐

















