Check for Ip Validity

Check for IP validity

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

#!/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 expr to do basically the same thing, using BRE instead of 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 expr assumes that your regex is anchored to the left-hand-side of the string, so the initial ^ is unnecessary.

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

#!/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:

#!/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.

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.

Validating IPv4 addresses with regexp

You've already got a working answer but just in case you are curious what was wrong with your original approach, the answer is that you need parentheses around your alternation otherwise the (\.|$) is only required if the number is less than 200.

'\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}\b'
^ ^

javascript regular expression to check for IP addresses

The regex you've got already has several problems:

Firstly, it contains dots. In regex, a dot means "match any character", where you need to match just an actual dot. For this, you need to escape it, so put a back-slash in front of the dots.

Secondly, but you're matching any three digits in each section. This means you'll match any number between 0 and 999, which obviously contains a lot of invalid IP address numbers.

This can be solved by making the number matching more complex; there are other answers on this site which explain how to do that, but frankly it's not worth the effort -- in my opinion, you'd be much better off splitting the string by the dots, and then just validating the four blocks as numeric integer ranges -- ie:

if(block >= 0 && block <= 255) {....}

Hope that helps.

Validate whether a string is valid for IP Address or not

You can pretty straightforward check it: split string to parts separated by dot and ensure it will be exactly four parts having values in range 1...255:

string s = "123.123.123.123";

var parts = s.Split('.');

bool isValid = parts.Length == 4
&& !parts.Any(
x =>
{
int y;
return Int32.TryParse(x, out y) && y > 255 || y < 1;
});

How to verify if a IP address is valid on Java?

In your specific scenario, you can add a filter and check the resulting arrays length:

String ipAddress = input.nextLine();
boolean ipValid = Arrays
.stream(ipAddress.split("\\."))
.mapToInt(Integer::parseInt)
.filter(x -> x >= 0 && x <= 255) // remove invalid numbers
.toArray().length == 4; // if the resulting length is 4, the ip is valid

Note: your approach will fail if Integer.parseInt throws an exception (i.e. if the user enters some letters), and will consider an IP valid even if there is some extra dot (like 192.168.0.1.)

Check if valid ip address from user input

You can use ipaddress module.

For example:

import ipaddress

while True:
try:
a = ipaddress.ip_address(input('Enter IP address: '))
break
except ValueError:
continue

print(a)

Prints (for example):

Enter IP address: s
Enter IP address: a
Enter IP address: 1.1.1.1
1.1.1.1

shell script + short syntax to verify valid IP

Don't reinvent the wheel.

use strict;
use warnings;
use Regexp::Common qw/net/;
# see http://search.cpan.org/dist/Regexp-Common/lib/Regexp/Common/net.pm

my $Address = '...';
# adapted from the module's synopsis
for ( $Address ) {
/$RE{net}{IPv4}/ and print "Dotted decimal IP address";
/$RE{net}{IPv4}{hex}/ and print "Dotted hexadecimal IP address";
/$RE{net}{IPv4}{oct}{-sep => ':'}/ and
print "Colon separated octal IP address";
/$RE{net}{IPv4}{bin}/ and print "Dotted binary IP address";
/$RE{net}{MAC}/ and print "MAC address";
/$RE{net}{MAC}{oct}{-sep => " "}/ and
print "Space separated octal MAC address";
}

Use the one you need.

If you cannot install the module, then just lurk through the module's code and get the correct regexp to use, depending on what kind of IP address you'd like to match.

Or, just use something like the above and call the same sub if the address matches any of the notations you want, or something along those lines.

Using it from your shell script would be along the lines of:

return perl -e'use Regexp::Common qw/net/;$ip=shift;if ($ip =~ /$RE{net}{IPv4}/){exit 0}else{exit 1}' "$Address";

The above would replace your complete "case" block.

Again, if you need to inline the regex in the perl script call you can do so by reading the module's code.



Related Topics



Leave a reply



Submit