1.要在AndroidManifest.xml里面设置用户上网权限
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
2.获得ipv6地址(类似fe80::b607:f9ff:fee5:487e的ip地址)
public String getDeviceIp() {
<span style="white-space:pre"> </span>try {
<span style="white-space:pre"> </span>for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
<span style="white-space:pre"> </span>NetworkInterface intf = en.nextElement();
<span style="white-space:pre"> </span>for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
<span style="white-space:pre"> </span>InetAddress inetAddress = enumIpAddr.nextElement();
<span style="white-space:pre"> </span>if (!inetAddress.isLoopbackAddress()) {
<span style="white-space:pre"> </span>return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
}
return "get ip failure";
}
3.获得ipv4地址(类似192.168.23.137的ip地址),只要加一个判断就可以了
public String getDeviceIp() {
<span style="white-space:pre"> </span>try {
<span style="white-space:pre"> </span>for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
<span style="white-space:pre"> </span>NetworkInterface intf = en.nextElement();
<span style="white-space:pre"> </span>for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
<span style="white-space:pre"> </span>InetAddress inetAddress = enumIpAddr.nextElement();
<span style="white-space:pre"> </span>if (!inetAddress.isLoopbackAddress()&& InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) {
<span style="white-space:pre"> </span>return inetAddress.getHostAddress().toString();
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>}
}
<span style="white-space:pre"> </span>} catch (SocketException ex) {
}
return "get ip failure";
}