Call: (480) 382-8464

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:


# extract multiple ipv4 address and perform dns lookup from a chunk of text
# export into a CSV
# perl > connections.csv
# then open with open office or similar csv viwer

use strict;
use warnings;

# you need 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";

10.1 (B) (adsfasdf) (SB-LAPTOP-70) Can be anything really – like log files, etc.  or a list, CSV, etc   Just paste your data to extract from below the (DATA) mark!! &&
Run this code and see what happs!

Tags: , , ,

Leave a Reply

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

Main Offers/Services

Hosting and website related services offered by Digital Crunch:

Managed VPS Hosting

Server Updates, Module/Software Installs, Firewall, Security, Hosting Management, Wordpress - let us manage it for you

Hosted Email

Setup and Maintain Business Class, Secure Email Hosting including spam protection and 25GB of storage space

Linux Consulting

Server Updates, Module/Software Installs, Firewall, Security, Hosting, Wordpress and Apps, anything related to Linux

Email Marketing Services

We broadcast your content to your list, capture leads for you, follow up on schedules, make more sales for you

Website Maintenance

Content updates, menu changes, graphics changes, adding content, getting links, building traffic, building sales funnels

Hosting Tutorials

Tutorials we've written for other customers that like to get their hands dirty and learn about hosting