Sunday, July 5, 2009

Perl Tutorial On Getting your External IP

Sometimes you need to find your external IP via perl, it's not that hard, but the only way I found to do it is kind of round about. You need to grab the page, then regex through it for your IP. Yeah this sucks, but it beats the hell out of the reception I got on #perl, but that's a diffrent post for a diffrent day. Ok so here are the steps:
On a unix or mac system you need to install lwp::simple first(On a windows system you can probably do this through ppm, just go to the cmd prompt and type ppm). To do that just run cpan:
sudo cpan
Then at the cpan prompt install LWP::Simple:
install LWP::Simple

Once that is installed, insert this bit of code into your code.

use LWP::Simple;
$whyip = qr/(Your IP address is \d+\.\d+\.\d+.\d+)/;
$content = get("");
if($content =~ $whyip){
print $&;

The first line imports the module.
The Second line declares a variable with the regular expression you are looking for.(Damnit, eneded a sentence with a preposition)
The third line says to "get" the website
The third line says, if the regexp we declared in the scond line is matched, then we do the next line.
This line says we print the matched expression.
The Last line closes the if statement.

This project is a small bit of a larger project I am working on that will eventually be revealed. Oh yeah and if you really want to know about #perl on freenode and why I am dissapointed with it, just head on over to

If this was relevant to your interests you may also like my arp sniffing in perl post.

**CAVEAT, I start my programs by typing:perl if you are doing ./ then you need a path she bang line like:
#!/usr/bin/perl <---for most linux systems #!/opt/local/bin/perl <-----for most mac systems
at the begining of your file

No comments: