Created
June 5, 2017 01:38
-
-
Save 5ZSQ/45a2b456a8d85e58493a421c61d1a8d8 to your computer and use it in GitHub Desktop.
Android - 获取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
/*获取设备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(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
请问开源协议整数是哪种呢?