验证IPv4 IP地址是否有效

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了验证IPv4 IP地址是否有效相关的知识,希望对你有一定的参考价值。

This code will validate not only the four octets contain between 1 and 3 numbers each, but also that the number they contain is between 0 and 255.

In all, there are 3 different regex's that I tried and all seem to work fine. The three regex's are:

1. m/^(dd?d?).(dd?d?).(dd?d?).(dd?d?)/
2. m/dd?d?.dd?d?.dd?d?.dd?d?/
3. m/d{1,2}.d{1,3}.d{1,3}.d{1,3}/

The first one is used below. Enjoy!!!
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6.  
  7. print("What is the IP Address you would like to validate: ");
  8. my $ipaddr = <STDIN>;
  9. chomp($ipaddr);
  10.  
  11.  
  12. if( $ipaddr =~ m/^(dd?d?).(dd?d?).(dd?d?).(dd?d?)$/ )
  13. {
  14. print("IP Address $ipaddr --> VALID FORMAT! ");
  15.  
  16. if($1 <= 255 && $2 <= 255 && $3 <= 255 && $4 <= 255)
  17. {
  18. print("IP address: $1.$2.$3.$4 --> All octets within range ");
  19. }
  20. else
  21. {
  22. print("One of the octets is out of range. All octets must contain a number between 0 and 255 ");
  23. }
  24. }
  25. else
  26. {
  27. print("IP Address $ipaddr --> NOT IN VALID FORMAT! ");
  28. }

以上是关于验证IPv4 IP地址是否有效的主要内容,如果未能解决你的问题,请参考以下文章

数据结构与算法之深入解析“验证IP地址”的求解思路与算法示例

算法判断IP地址是不是合法的,包含IPv4和IPv6

算法判断IP地址是不是合法的,包含IPv4和IPv6

在 Java 中验证 IPv4 地址

判断是否IPV4地址最简单有效的办法

你如何在 Typescript 中验证 IP 地址?