checking if an IP is valid.

echo $IP | egrep '^(([0-9]{1,2}|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}([0-9]{1,2}|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$'

0
2015-10-19 18:06:32

What Others Think

At first I thought this was a little hackish, but the other example has more problems. Sometimes keeping it simple and a a little bit longer works better. This works and is simple assuming you don't care about actually matching usable IPs because that will depend on the subnet mask. The first and last IP specified in a given network can't be used and might not be considered, "valid" they might still be valid but still not usable depending on how you want to define what a valid IP is. The first IP is used as the network ID and the last IP is used as the broadcast address. Those numbers are often going to be 0 and 255 for the last number in the last octet but it depends on the subnet mask. It's actually good practice to just not use 0 or 255 in the last octet even though using sometimes 0 can be valid and I know admins who intentionally use it for things like their DHCP server or a DNS server. There's plenty of talk about this online of course.
sonic · 523 weeks and 4 days ago

What do you think?

Any thoughts on this command? Does it work on your machine? Can you do the same thing with only 14 characters?

You must be signed in to comment.

What's this?

commandlinefu.com is the place to record those command-line gems that you return to again and again. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.

Share Your Commands



Stay in the loop…

Follow the Tweets.

Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.

» http://twitter.com/commandlinefu
» http://twitter.com/commandlinefu3
» http://twitter.com/commandlinefu10

Subscribe to the feeds.

Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):

Subscribe to the feed for: