Linux 检查 IP 有效性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13777387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 17:59:36  来源:igfitidea点击:

Check for IP validity

linuxshell

提问by AlwaysALearner

How do I check the validity of an IP address in a shell script, that is within the range 0.0.0.0to 255.255.255.255?

如何检查shell脚本中的IP地址的有效性,这是该范围内0.0.0.0255.255.255.255

采纳答案by ghoti

If you're using bash, you can do a simple regex match for the pattern, without validating the quads:

如果您使用 bash,则可以对模式进行简单的正则表达式匹配,而无需验证四边形:

#!/usr/bin/env bash

ip=1.2.3.4

if [[ $ip =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  echo "success"
else
  echo "fail"
fi

If you're stuck with a POSIX shell, then you can use exprto do basically the same thing, using BRE instead of ERE:

如果您坚持使用 POSIX shell,那么您可以使用exprBRE 而不是 ERE 来做基本相同的事情:

#!/bin/sh

ip=1.2.3.4

if expr "$ip" : '[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*$' >/dev/null; then
  echo "success"
else
  echo "fail"
fi

Note that exprassumes that your regex is anchored to the left-hand-side of the string, so the initial ^is unnecessary.

请注意,expr假设您的正则表达式锚定在字符串的左侧,因此^不需要初始值。

If it's important to verify that each quad is less than 256, you'll obviously require more code:

如果验证每个四边形小于 256 很重要,您显然需要更多代码:

#!/bin/sh

ip=${1:-1.2.3.4}

if expr "$ip" : '[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*$' >/dev/null; then
  for i in 1 2 3 4; do
    if [ $(echo "$ip" | cut -d. -f$i) -gt 255 ]; then
      echo "fail ($ip)"
      exit 1
    fi
  done
  echo "success ($ip)"
  exit 0
else
  echo "fail ($ip)"
  exit 1
fi

Or perhaps even with fewer pipes:

或者甚至可以使用更少的管道:

#!/bin/sh

ip=${1:-1.2.3.4}

if expr "$ip" : '[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*$' >/dev/null; then
  IFS=.
  set $ip
  for quad in 1 2 3 4; do
    if eval [ $$quad -gt 255 ]; then
      echo "fail ($ip)"
      exit 1
    fi
  done
  echo "success ($ip)"
  exit 0
else
  echo "fail ($ip)"
  exit 1
fi

Or again, if your shell is bash, you could use a cumbersome regular expression for quad validation if you're not fond of arithmetic:

或者,如果您的 shell 是 bash,如果您不喜欢算术,则可以使用繁琐的正则表达式进行四元验证:

#!/usr/bin/env bash

ip=${1:-1.2.3.4}

re='^(0*(1?[0-9]{1,2}|2([0-4][0-9]|5[0-5]))\.){3}'
 re+='0*(1?[0-9]{1,2}|2([??0-4][0-9]|5[0-5]))$'

if [[ $ip =~ $re ]]; then
  echo "success"
else
  echo "fail"
fi

This could also be expressed in BRE, but that's more typing than I have in my fingers.

这也可以用 BRE 来表达,但那比我用手指打字要多。

And lastly, if you like the idea of putting this functionality ... in a function:

最后,如果你喜欢把这个功能......放在一个函数中的想法:

#!/usr/bin/env bash

ip=${1:-1.2.3.4}

ipvalid() {
  # Set up local variables
  local ip=${1:-1.2.3.4}
  local IFS=.; local -a a=($ip)
  # Start with a regex format test
  [[ $ip =~ ^[0-9]+(\.[0-9]+){3}$ ]] || return 1
  # Test values of quads
  local quad
  for quad in {0..3}; do
    [[ "${a[$quad]}" -gt 255 ]] && return 1
  done
  return 0
}

if ipvalid "$ip"; then
  echo "success ($ip)"
  exit 0
else
  echo "fail ($ip)"
  exit 1
fi

There are many ways you could do this. I've shown you just a few.

有很多方法可以做到这一点。我只给你看了几个。

回答by shannonman

The script Validating an IP Address in a Bash Scriptby Mitch Frazier does what you want to do:

Mitch Frazier编写的Validating an IP Address in a Bash Script 脚本执行您想要执行的操作:

function valid_ip()
{
local  ip=
local  stat=1

if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
    OIFS=$IFS
    IFS='.'
    ip=($ip)
    IFS=$OIFS
    [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
        && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
    stat=$?
fi
return $stat
}
function valid_ip()
{
local  ip=
local  stat=1

if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
    OIFS=$IFS
    IFS='.'
    ip=($ip)
    IFS=$OIFS
    [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
        && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
    stat=$?
fi
return $stat
}

回答by glenn Hymanman

Perl has a great module Regexp::Commonfor validating various things:

Perl 有一个很棒的模块Regexp::Common用于验证各种事情:

perl -MRegexp::Common=net -e 'exit(shift() !~ /^$RE{net}{IPv4}$/)' $ipaddr

You may need to sudo cpan install Regexp::Commonfirst

您可能需要sudo cpan install Regexp::Common

I'd wrap it in a function:

我会把它包装在一个函数中:

valid_ip() {
  perl -MRegexp::Common=net -e 'exit(shift() !~ /^$RE{net}{IPv4}$/)' ""
}

if valid_ip 123.234.345.456; then
  echo OK
else
  echo INVALID
fi

回答by William Pursell

The typical solutions for this all seem to use regular expressions, but it occurs to me that it might be a better approach to do something like:

对此的典型解决方案似乎都使​​用正则表达式,但在我看来,执行以下操作可能是更好的方法:

if echo "$ip" | { IFS=. read a b c d e;
    test "$a" -ge 0 && test "$a" -le 255 &&
    test "$b" -ge 0 && test "$b" -le 255 &&
    test "$c" -ge 0 && test "$c" -le 255 &&
    test "$d" -ge 0 && test "$d" -le 255 &&
    test -z "$e"; }; then echo is valid; fi

回答by Nasimuddin Ansari

Use ipcalc

使用 ipcalc

$ ipcalc -cs 10.10.10.257 && echo vail_ip || echo invalid_ip
invalid_ip

回答by Jon

This single regex should validate only those addresses between 0.0.0.0 and 255.255.255.255:

这个单一的正则表达式应该只验证 0.0.0.0 和 255.255.255.255 之间的那些地址:

#!/bin/bash

ip="1.2.3.4"

if [[ "$ip" =~ ^(([1-9]?[0-9]|1[0-9][0-9]|2([0-4][0-9]|5[0-5]))\.){3}([1-9]?[0-9]|1[0-9][0-9]|2([0-4][0-9]|5[0-5]))$ ]]; then
  echo "success"
else
  echo "fail"
fi

回答by TJW

#!/bin/bash
read -p " ip: " req_ipadr
#
ip_full=$(echo $req_ipadr | sed -n 's/^\(\(\([1-9][0-9]\?\|[1][0-9]\{0,2\}\|[2][0-4][0-9]\|[2][5][0-4]\)\.\)\{3\}\([1-9][0-9]\?\|[1][0-9]\{0,2\}\|[2][0-4][0-9]\|[2][5][0-4]\)\)$//p')
#
[ "$ip_full" != "" ] && echo "$req_ipadr vaild ip" || echo "$req_ipadr invaild ip"

回答by DirectedSoul

i tweaked all the codes and found this to be helpful.

我调整了所有代码,发现这很有帮助。

#!/bin/bash

ip="256.10.10.100"

if [[ "$ip" =~ (([01]{,1}[0-9]{1,2}|2[0-4][0-9]|25[0-5])\.([01]{,1}[0-9]{1,2}|2[0-4][0-9]|25[0-5])\.([01]{,1}[0-9]{1,2}|2[0-4][0-9]|25[0-5])\.([01]{,1}[0-9]{1,2}|2[0-4][0-9]|25[0-5]))$ ]]; then
  echo "success"
else
  echo "fail"
fi

回答by Adam Bowen

I prefer to use ipcalc to do this, as long as my script doesn't have to be portable.

我更喜欢使用 ipcalc 来做到这一点,只要我的脚本不必是可移植的。

ipcalc 1.1.1.355                                                                         
INVALID ADDRESS: 1.1.1.355

Address:   192.168.1.1          11000000.10101000.00000001. 00000001
Netmask:   255.255.255.0 = 24   11111111.11111111.11111111. 00000000
Wildcard:  0.0.0.255            00000000.00000000.00000000. 11111111
=>
Network:   192.168.1.0/24       11000000.10101000.00000001. 00000000
HostMin:   192.168.1.1          11000000.10101000.00000001. 00000001
HostMax:   192.168.1.254        11000000.10101000.00000001. 11111110
Broadcast: 192.168.1.255        11000000.10101000.00000001. 11111111
Hosts/Net: 254                   Class C, Private Internet

There is a great page showing how to use it in scripting, etc, here: SleeplessBeastie's Notes

有一个很棒的页面展示了如何在脚本等中使用它,这里是: SleeplessBeastie's Notes

回答by Naresh Joshi

You can just copy the following code and change body of if else control as per your need

您只需复制以下代码并根据需要更改 if else 控件的主体

function checkIP(){
echo "Checking IP Integrity"    
ip=
byte1=`echo "$ip"|xargs|cut -d "." -f1`
byte2=`echo "$ip"|xargs|cut -d "." -f2`
byte3=`echo "$ip"|xargs|cut -d "." -f3`
byte4=`echo "$ip"|xargs|cut -d "." -f4`


if [[  $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$  && $byte1 -ge 0 && $byte1 -le 255 && $byte2 -ge 0 && $byte2 -le 255 && $byte3 -ge 0 && $byte3 -le 255 && $byte4 -ge 0 && $byte4 -le 255 ]]
then
    echo "IP is correct"
else
    echo "This Doesn't look like a valid IP Address : $ip" 
fi
}
checkIP $myIP 

Calling the method with IP Address stored in a variable named myIP.

使用存储在名为 myIP 的变量中的 IP 地址调用方法。

$ip =~ ^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$ - This part makes sure that IP consists of 4 blocks separated by a dot(.) but every block here is allowed to range from 0 - 999

$ip =~ ^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$ -这部分确保 IP 由 4 个由点(.)分隔的块组成,但这里的每个块都允许在 0 - 999 之间

Since desired range of every block would be 0 - 255, to make sure of that below line can be used.

由于每个块的所需范围是 0 - 255,以确保可以使用下面的行。

$byte1 -ge 0 && $byte1 -le 255 && $byte2 -ge 0 && $byte2 -le 255 && $byte3 -ge 0 && $byte3 -le 255 && $byte4 -ge 0 && $byte4 -le 255

$byte1 -ge 0 && $byte1 -le 255 && $byte2 -ge 0 && $byte2 -le 255 && $byte3 -ge 0 && $byte3 -le 255 && $byte4 -ge 0 && $byte4 -le 255