Get your IP address with Perl
So. You want to find your external IP address for use in a perl script. This falls into the "simple things that should be easy" category, but the devil's in the details. I'll discuss a few scenarios, and give you some simple scripts that should help you if you're trying to do this behind a router / NAT setup.
- Scenario 1: Named Machine
This is the simplest scenario, and assumes you're on a machine with a fully qualified domain name (e.g. geekuprising.com). All you need to do is use the standard IO::Socket module to resolve your name and parse out your IP address.
$hostname="collispuro.net"; #change this to your hostname
- Scenario 2: Non-named machine, not behind a router
This is a little more difficult. This should work on *nix variants (BSD, linux, etc.), but it might not. This assumes that the external IP is attached to the machine you're on. Basically, what I do is shell out to "ifconfig" and retrieve the external IP address directly from the adapter.
# the interface is what your external IP is bound to- eth0 or ppp0, most likely
# if you're on ADSL/dialup, it's probably ppp0
# path to ifconfig
@lines=qx|$ifconfig $interface| or die("Can't get info from ifconfig: ".$!);
- Scenario 3: Machine behind router
If you have ADSL/cable with a router, you probably have a dynamically assigned internal IP on your machine. This set of scripts will help you automagically get your IP in combination with a box outside your router.
Because your internal machine will have an internal IP assigned by the router, this one is tricky. My suggestion- if you want to run a service on your box, figure out "one-to-one NAT" translation, and give your machine a static internal IP via your router. You can then route external requests directly to your box sitting on the internal IP, allowing you to run services predictably.
Because your machine has the internal IP bound to it's adapter, and doesn't have a full qualified domain name, you have to look outside your router to get your IP. That's what this pair of scripts does. You'll need to have the "ipreport.pl" script set up on some other box, external to your router. You then ding the "ipreport.pl" script with the "ipget.pl" script from the box whose IP you want to sniff out, and voila! You've got your external IP!
# ipreport.pl- the script that sits external to your router
# ipget.pl- the script that retrieves your IP for you. Run this on the box
# whose IP you want to figure out. You can make this part of a larger program,