Monday, December 14, 2015

Chunk IPv4 range into multiple sub-chunks

One of my non-programmer-but-in-IT friends came to me last week, asking help to chunk a range of IPv4 addresses into N small chunks. And, here's the PHP code I came up with within 10 mins.

What it simply does is, explode the input range, and convert start and end IP address into long, using ip2long(). Then, using range() expand it into a whole list. Once that is done, then decide number of elements that should go into each chunk - remember, the optional argument to this function tells how many chunks are to be prepared. the formula is there on code line number 11.

Once you have this number, call array_chunk() to create chunks. Finally, iterate over them, get start and end IP of each of them (which are still long numbers), convert them back to IPv4 address using long2ip() and create the range string for them.

Do you find it useful? Copy it! Have any suggestion, let me know in the comment!!

Wednesday, May 13, 2015

Ordinal Number

Here is a PHP function to get the ordinal number. Pass it a number, and it will return a textual number suffixed with either of "st" (like 1st), "nd" (like 2nd), "rd" (like 3rd), "th" (like 4th) etc.

Grep - before and after

The grep is a command line utility for searching plain-text data sets for lines matching the given regular expression. And those using Linux (or some or other flavor of this OS), must have used this command. Here are two useful options of this command: -A for After and -B for Before. Both take a number as their value.

As their names suggest, -A gives you matching line and N lines after the matching line, similarly, -B gives you matching line and N lines before the matching line.

You can also combine both these options into single command. And, if your -A and -B values are same, then you can simply use -C option. C stands for Count.