--#-- Snap to it! --#-- If we wait until we make our ISP connection, then our robot will fortuitously find an IP address on its first call of ifconfig. But if we want this senseless creature to automagically do our work, we need to figure a way he can be notified when the connection is successfully established. Unfortunately, we don't really have a good way of knowing exactly when the ISP connection is established except by watching for it.

On a Linux or other Unix system, it's easy enough to watch for messages written to the system log. On my Linux systems, I'll usually open a shell and issue the command tail -f /var/log/messages. My ppp script writes progress reports there, ending with the new IP address when a connection is made.

In our robot's case, the best bet for learning when the connection has been made is to keep making blind stabs at obtaining the new IP address until he's successful.

In other words, let's put our robot code into a loop that repeats until it finds an IP address:

while (1) { $ip = `/sbin/ifconfig`; $ip =~ s/.*(ppp0)(.*)/$2/s; if ($1) { .... # do our stuff here exit(0); } }
Now, this is the real world and what happens in the real world when you dial up your ISP? Right, busy signals, no answer, aborted connections. Life as usual. Our robot's an idiot and will go blythly on trying to discover its IP address no matter how many times somebody hangs up on him. So, let's add a count variable to the loop and put the fool out of his misery if he hasn't gotten an address by 50 tries or so.

While we're at it, let's add a sleep line to the code in between tries. There's no sense in going at this thing at break-neck speed.

When I first wrote this code, I had it write a few lines to STDOUT to report when it made a connection and how many tries it took. The code invariably got an IP address around try 10 or 11. As I was telling it to sleep 4 seconds between tries, that indicated it took an average of 40 seconds to connect.

Which makes sense. It generally takes at least 30 seconds for a dial-up script to make and connection and go through its handshake with the remote system. So, let's add a 30-second sleep even before the code enters it loop.

What we wind up with is 41 lines of Perl.

But, ah! you say. How does this run every time I dial up? On to the finish to to the tale: