Categories
Perl

Extract IPv4 Address From Text Using Perl

I had a list of IP address and wanted to know what they were – but I didn’t want to do a DNS lookup by hand on each. The list I had was really a chunk of text with IPv4 addresses all over in it. Here is how I extracted them for the report:

I had a list of IP address and wanted to know what they were – but I didn’t want to do a DNS lookup by hand on each. The list I had was really a chunk of text with IPv4 addresses all over in it. Here is how I extracted them for the report:


#!/usr/bin/perl
# extract multiple ipv4 address and perform dns lookup from a chunk of text
# export into a CSV
# perl connections.pl > connections.csv
# then open with open office or similar csv viwer
use strict;
use warnings;
# you need Socket.pm to do this, to install when not behind a proxy:
# perl –MCPAN –e shell
# cpan> install Socket
# exit
use Socket;
my %ips;
#process line by line:
while(<DATA>) {
# each time we find an IP
# this regex is designed to be all on one line.
while (/(?!0+\.0+\.0+\.0+$)(([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5]))/g) {
# put whatever we just matched into a more permanent variable
my $ip = $1;
# put in a hash to remove duplicates
$ips{$ip} = $ip;
}
}
# loop over the unique IP addrs
foreach my $key (sort keys %ips) {
print $key;
# pretending that I don't want to see 192 or 10 net stuff
unless (($key =~ m/^192/) or ($key =~ m/^10\./)) {
# array of 4 octets
my @numbers = split (/\./, $key);
# packed into the format gethostbyaddr likes
my $ipPacked = pack("C4", @numbers);
# the FQDN, or 'unknown'
my $name = gethostbyaddr( $ipPacked, 2 ) || 'unknown';
print ",$name";
# end of the "unless" swich
} else { print ",unknown" }
# newline
print "\n";
}
__DATA__
10.1 (B) 192.168.10.1 10.20.0.67 (adsfasdf) 192.168.10.1
10.0.0.126 (SB-LAPTOP-70) Can be anything really – like log files, etc.
99.99.99.99  or a list, CSV, etc   Just paste your data to extract from below the (DATA) mark!!
4.2.2.2 4.2.2.2 4.2.2.2 && 4.2.2.2 4.2.2.2 4.2.2.2
Run this code and see what happs!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.