# shell code to check IP v4



## fluca1978 (Jul 2, 2012)

Hi,

Is there any tool or part of a script that I can use in my shell scripts to check if an IP v4 is correct (dotted-quad and in the right form) and possibly if it is a range {IP, Mask}?


----------



## ondra_knezour (Jul 2, 2012)

First one should be easy, just some form of regular expression like 

```
[1-255]\.[0-255]\.[0-255]\.[0-255]
```
should be fine (except not checking for reserved address space etc.)

Second is more challenging, I will try to split octets, transform them to binary form with bc(), join them and check if

Input matches range in first X bites defined by mask
Rest of input (non-masked part) is between rest of network address and all 1


----------



## wblock@ (Jul 2, 2012)

ondra_knezour said:
			
		

> First one should be easy, just some form of regular expression like
> 
> ```
> [1-255]\.[0-255]\.[0-255]\.[0-255]
> ...



Regex ranges only work on single characters, though.  Splitting out the octets is probably a better way.


```
input="192.168.1.1"

IFS='.'
for octet in $input; do
  if [ $octet > 255 ]; then
    echo "$octet greater than 255"
    exit
  fi
done
```

Note that this doesn't count the octets, since--technically--four are not required.  That's another test that a more-strict script could do.

Or just go with Perl and use net-mgmt/p5-Data-Validate-IP.


----------



## kpa (Jul 2, 2012)

This is for perl(1) but I think you can easily adapt it to for example sed(1) 

```
((25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)
```


----------

