Skip to content

Instantly share code, notes, and snippets.

@jaytaylor
Created February 4, 2014 21:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaytaylor/8812713 to your computer and use it in GitHub Desktop.
Save jaytaylor/8812713 to your computer and use it in GitHub Desktop.
IPv4 addressing tools to convert between IP address <=> IP Number.
#!/usr/bin/env perl
##
# @author Jay Taylor [@jtaylor]
#
# @date 2014-02-04
#
# @description Converts an IPv4 address into an IP number, the unsigned 32-bit numeric representation of an IPv4 address.
#
# Try getting address from argv.
$ipAddress = $ARGV[0];
if ($ipAddress == 0) {
# Otherwise read from stdin.
while (<>) {
$ipAddress = $_;
}
}
# Strip leading and/or trailing whitespace.
$ipAddress =~ s/^\s*([^\s]*)\s*$/$1/;
@octets = split(/\./, $ipAddress);
$ipNumber = ($octets[0] * 1 << 24) + ($octets[1] * 1 << 16) + ($octets[2] * 1 << 8) + ($octets[3] * 1);
print "$ipNumber";
#!/usr/bin/env perl
##
# @author Jay Taylor [@jtaylor]
#
# @date 2014-02-04
#
# @description Converts an IPv4 number into an IP address, the (more) human-readable representation consisting of a set of four 4-byte sequences (8 bits for each sequece).
#
# Try getting address from argv.
$ipNumber = $ARGV[0];
if ($ipNumber == 0) {
# Otherwise read from stdin.
while (<>) {
$ipNumber = $_;
}
}
# Strip leading and/or trailing whitespace.
$ipNumber =~ s/^\s*([^\s]*)\s*$/$1/;
# Ensure $ipNumber is an integer.
$ipNumber *= 1;
$ipAddress = join(".", $ipNumber >> 24 & 0xFF, $ipNumber >> 16 & 0xFF, $ipNumber >> 8 & 0xFF, $ipNumber & 0xFF);
print "$ipAddress";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment