Created
May 10, 2018 08:21
-
-
Save xingstarx/e7ec9d6934a153eb6938b85a98a389cc to your computer and use it in GitHub Desktop.
NetWorkUtils 获取客户端真实ip
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ""; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
需要添加权限
copy from https://stackoverflow.com/a/13007325/5279354