Skip to content

Instantly share code, notes, and snippets.

@xingstarx
Created May 10, 2018 08:21
Show Gist options
  • Save xingstarx/e7ec9d6934a153eb6938b85a98a389cc to your computer and use it in GitHub Desktop.
Save xingstarx/e7ec9d6934a153eb6938b85a98a389cc to your computer and use it in GitHub Desktop.
NetWorkUtils 获取客户端真实ip
public class NetWorkUtils {
public static String getIPAddress(boolean useIPv4) {
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces) {
List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
for (InetAddress addr : addrs) {
if (!addr.isLoopbackAddress()) {
String sAddr = addr.getHostAddress();
//boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
boolean isIPv4 = sAddr.indexOf(':')<0;
if (useIPv4) {
if (isIPv4) {
return sAddr;
}
} else {
if (!isIPv4) {
int delim = sAddr.indexOf('%'); // drop ip6 zone suffix
return delim<0 ? sAddr.toUpperCase() : sAddr.substring(0, delim).toUpperCase();
}
}
}
}
}
return "";
}
}
@xingstarx
Copy link
Author

xingstarx commented May 10, 2018

需要添加权限

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

copy from https://stackoverflow.com/a/13007325/5279354

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment