Skip to content

Instantly share code, notes, and snippets.

@5ZSQ
Created June 5, 2017 01:38
Show Gist options
  • Save 5ZSQ/45a2b456a8d85e58493a421c61d1a8d8 to your computer and use it in GitHub Desktop.
Save 5ZSQ/45a2b456a8d85e58493a421c61d1a8d8 to your computer and use it in GitHub Desktop.
Android - 获取ip地址
/*获取设备IPv4地址对应的字符串*/
public static String getIpAddressString() {
try {
for (Enumeration<NetworkInterface> enNetI = NetworkInterface
.getNetworkInterfaces(); enNetI.hasMoreElements(); ) {
NetworkInterface netI = enNetI.nextElement();
for (Enumeration<InetAddress> enumIpAddr = netI
.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (inetAddress instanceof Inet4Address && !inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return "0.0.0.0";
}
/*判断字符串是否为一个合法的IPv4地址*/
public static boolean isIPv4Address(String address) {
String regex = "(2[5][0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})"
+ "\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})"
+ "\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})"
+ "\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(address);
return m.matches();
}
@TommyLemon
Copy link

请问开源协议整数是哪种呢?

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