在 Java 中验证 IPv4 字符串
Bellow 方法正在验证字符串是否是正确的 IPv4 地址,如果有效则返回 true。正则表达式和优雅方面的任何改进将不胜感激:
public static boolean validIP(String ip) {
if (ip == null || ip.isEmpty()) return false;
ip = ip.trim();
if ((ip.length() < 6) & (ip.length() > 15)) return false;
try {
Pattern pattern = Pattern.compile("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");
Matcher matcher = pattern.matcher(ip);
return matcher.matches();
} catch (PatternSyntaxException ex) {
return false;
}
}
Bellow method is validating if string is correct IPv4 address it returns true if it is valid. Any improvements in regex and elegance would be very appreciated:
public static boolean validIP(String ip) {
if (ip == null || ip.isEmpty()) return false;
ip = ip.trim();
if ((ip.length() < 6) & (ip.length() > 15)) return false;
try {
Pattern pattern = Pattern.compile("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");
Matcher matcher = pattern.matcher(ip);
return matcher.matches();
} catch (PatternSyntaxException ex) {
return false;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(17)
这是一种更容易阅读、效率稍低的方法。
Here is an easier-to-read, slightly less efficient, way you could go about it.
更新: Commons-HttpClient 及其后继者 HttpComponents-HttpClient 已采用此功能。您可以像这样使用它的这个版本:
InetAddressUtils.isIPv4Address(Str)
。Apache Commons Validator 的开发版本有一个
InetAddressValidator
类,它有一个isValidInet4Address(String)
方法执行检查以查看给定的String
是否是有效的 IPv4 地址。源代码可以从存储库中查看,因此如果您认为有任何改进,这可能会提供一些改进的想法。
快速浏览一下所提供的代码就会发现,您的方法正在每次调用该方法时编译一个
Pattern
。我会将Pattern
类移出到static
字段,以避免每次调用时昂贵的模式编译过程。UPDATE: Commons-HttpClient and its successor HttpComponents-HttpClient have adopted this functionality. You can utilize this version of it like so:
InetAddressUtils.isIPv4Address(Str)
.The development version of Apache Commons Validator has a
InetAddressValidator
class which has aisValidInet4Address(String)
method to perform a check to see that an givenString
is a valid IPv4 address.The source code can be viewed from the repository, so that might provide some ideas for improvements, if you feel there are any.
A quick glance at the provided code shows that your method is compiling a
Pattern
on each invocation of the method. I would move thatPattern
class out to astatic
field to avoid the costly pattern compilation process on each call.如果您想使用已发布版本同时支持 IPv4 和 IPv6 的库,可以使用 番石榴
If you want to use a library with a released version suppporting both IPv4 and IPv6 support, you can use Guava
如果您不介意对
www.example.com
等无效 IP 地址使用 dns 解析,则可以使用 InetAddress 要检查的方法:该方法检查它是否是 Inet4Address 的实例,如果该参数是 IP 地址而不是主机名。
如果您期望使用大量主机名作为参数,请注意此实现使用 DNS 来尝试解析它。这可能是一个性能问题。
否则你可能会达到高峰
boolean sun.net.util.IPAddressUtil.isIPv4LiteralAddress(String src)
如何解析字符串以进行 IPv4 检查。If you don't mind using dns resolution on invalid ip-addresses like
www.example.com
, you can use the InetAddress methods to check:The method checks if it is an instance of Inet4Address and if the parameter was the ip-address and not the hostname.
If you expect a lot of hostnames as parameters, beware that this implementation uses DNS to try to resolve it. This might be a performance concern.
Otherwise you can have a peak into
boolean sun.net.util.IPAddressUtil.isIPv4LiteralAddress(String src)
how the String is parsed there for IPv4-check.下面是一个使用 Java 8 流来检查地址是否由 0 到 255(含)之间的 4 个数字组成的解决方案,并用点分隔:
Here's a solution that uses Java 8 streams to check that the address consists of exactly 4 numbers between 0 and 255 inclusive, separated by dots:
从 this 中查找正则表达式示例
Find regex example from this
认为这个解决方案非常优雅,尽管需要花一点时间才能理解它。
基本思想是获取一个子字符串并验证它。
请注意,我交换了 x 和 y,因为子字符串的开头始终是最后一个加 1 的结尾。
这个解决方案是比正则表达式变体快大约 20 倍,比分割快 2 倍。
如果您知道会有很多错误的 IP,请考虑在第一个 if 下面添加以下代码。这将使代码速度慢 1.5 倍,但如果出现错误,速度会提高 700 倍
In think this solution is quite elegant, although it takes a minute to understand it.
The basic idea is to take a sub-string and than validate it.
Please note that I switch x and y, since the start of a sub-string will always be the end of the last one plus 1.
This solution is about 20x faster than a regex variant and 2x faster than splitting.
If you know that you'll have a lot wrong IPs consider adding the following code below the first if. This will make the code 1.5x slower but in case of an error improve it by 700x
尝试使用以下 IPv4 正则表达式
希望它有帮助:)
Try using the following regrex for IPv4
hope it helps :)
如果您使用问题中的代码,您需要将该行更改
为:
If you use the code in the question, you'll want to change the line:
to
大多数答案(除了 Michael Konietzka 的答案)都是错误的:例如,10.8 是一个有效的 IP4 地址(10.0.0.8 的简写)。
请参阅IP 地址的文本表示 Java 规范。
如在参考文献中可以看到的,为了检查数字表示,可能有 1 到 4 个部分,并且在每种情况下对这些部分应用不同的限制。
Most of the answers (except that of Michael Konietzka) are wrong: 10.8, for instance, is a valid IP4 address (a shorthand for 10.0.0.8).
SeeTextual representation of IP addresses in the Java specifications.
As may be seen in the reference, to check a numeric representation, there may be 1 to 4 parts, and in each case different limitations on the parts apply.
我认为正确的方法是构建一个 IPAddress 类并通过为其提供 IP 地址的字符串表示形式来实例化它。
通过这种方式,您可以将不同的验证步骤拆分为实例方法,并进行一些关注点分离。
例如,这里通常是它自己的方法,简单地调用它
isEmpty
:此外,这应该是一个单独的方法,您可以调用它
hasProbableLength
。这里发生了很多事情。我会尝试打破这个问题,也许尝试完全跳过正则表达式。
我首先将字符串按点分开,然后看到正好得到四个组。调用此方法
divideIntoGroups
然后,我将验证每个组的值是否在 0 到 255 之间。调用此方法
validateGroups
现在您已经有了这个方法,如果您想扩展这个类来查找 IP 是否是本地主机或者是否是广播地址,这很容易做到。这就是关注点分离为您提供的功能。
您还可以准确判断哪一项验证规则在 IP 地址字符串验证中被破坏。正则表达式不会的东西。
I think the proper way is to build an
IPAddress
class and instanciate it by giving it a string representation of the the ip address.This way you can split out the different validation steps into instance methods and get some separation of concern going.
For instance, this here is typically it's own method, call this simply
isEmpty
:Also this should be a separate method, you could call this one
hasProbableLength
.Here there are lots of things going on. I would try to break this up and perhaps try to skip the regex completely.
I would first split the string on dots and see that I get exactly four groups. Call this method
divideIntoGroups
I would then validate each of the groups for being a value between 0 and 255. Call this method
validateGroups
Now that you have this, if you ever want to extend this class to also look for if the IP is localhost or if it is a broadcast address, it is pretty easy to do this. This is what separation of concerns gives you.
You can also tell exactly which one of your validation rules was broken in the validation of the IP address string. Something that regex will not.
IPAddress Java 库 会做到这一点。 javadoc 可在链接中找到。免责声明:我是项目经理。
该库透明地支持 IPv4 和 IPv6,因此验证两者的工作方式如下,并且它还支持 CIDR 前缀长度 IPC4 地址。它支持更不寻常的格式,例如 inet_aton (例如,在另一个答案中提到了 10.8)
验证地址是否有效:
The IPAddress Java library will do it. The javadoc is available at the link. Disclaimer: I am the project manager.
This library supports IPv4 and IPv6 transparently, so validating either works the same below, and it also supports CIDR prefix-length IPC4 addresses as well. It supports the more unusual formats like inet_aton (for example 10.8 was mentioned in another answer here)
Verify if an address is valid:
我发现检查给定 ip 在 ipv4 中是否正确的最简单方法是使用 commons-validator-1.4.0.jar 有类:--
InetAddressValidator
例如
使用这个简单的正则表达式:--
Most simple way I found to check given ip is correctly in ipv4 is to use commons-validator-1.4.0.jar has class:--
InetAddressValidator
E.g.
which uses this simple regex :--
这将对你有用,
It will be useful for you,
我建议使用您正在开发的平台/框架上可用的内容。
如果您认为没有什么足够好,那么您可能只想将已编译的正则表达式添加到辅助类中。例如, Android 框架的实现方式如下:
I would suggest using what's available on the platform/framework you are developing.
If there's nothing you consider good enough, then you might just want to add a compiled regex to a helper class. For instance, here's how the Android framework does it:
与 coobird 相同的答案。只需将 localhost 添加到语句中即可。大多数环境都将“localhost”作为有效的主机名。它不是 ipv4 格式,但应包含它以考虑有效性。
same answer as coobird. Just add localhost to the statement. Most of the environments takes 'localhost' as a valid host name. It is not a ipv4 format but it should be included to consider validity.