What regex can I use to match any valid IP-address

2019-04-06 11:02发布

What regex can I use to match any valid IP-address represented in dot-decimal notation?

10条回答
做个烂人
2楼-- · 2019-04-06 11:20
if($ip=~/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/ &&(($1<=255  && $2<=255 && $3<=255  &&$4<=255 )))
     {
         print "valid\n";
     }
     else
     {
         print "Invalid\n";
     }
查看更多
三岁会撩人
3楼-- · 2019-04-06 11:22

IPv4 ip validation with port number

if ( $ip =~ /(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(:(\d{1,5}))?/ )
{
    if( $1 > 255 || $2 > 255 || $3 > 255 || $4 > 255)
    {
        print "invalid ip\n";
        return ;
    }
    if( ( defined $6) && ( $6 > 65536 ))
    {
        print "invalid port\n";
        return ;
    }
    print "valid ip \n";
}
else
{
    print "invalid ip\n";
    return ;
}
查看更多
放我归山
4楼-- · 2019-04-06 11:26
(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])

Actually matches some invalid IP addresses, such as:

192.168.00.001

A slightly more refined solution would be:

(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$
查看更多
SAY GOODBYE
6楼-- · 2019-04-06 11:29

$ip='123.0.0.1';
if($ip=~/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/ &&((($1<=255 && $1 > 0) && $2<=255 && $3<=255  &&$4<=255 )))
 {
     print "valid\n";
 }
 else
 {
     print "Invalid\n";
 }

Blockquote

Here in this case we are validating 0.0.0.0 will not be consider the valid IP. and supporting all remaing IP's upto 1.0.0.0 to 255.255.255.255`enter code here

Blockquote

查看更多
聊天终结者
7楼-- · 2019-04-06 11:37

If you can leave a perl module behind - then do it.

what about:

if( $ip=~ m/^(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)/ && 
          ( $1 <= 255 && $2 <= 255 && $3 <= 255 && $4 <= 255 )
) {    
    print "valid IP.";
}
查看更多
登录 后发表回答