| |
I've got my number
I'm going to assume you obtain your IP address through a dial-up to an
Internet Service Provider. If you don't, that's OK. Just know what device
your connection is on. On Linux and other Unices, you can determine whether
you are connected (and, at what address) by issuing the ifconfig
command. This command frequently lives in /sbin (YMMV), and you may have to
give it the full path. When you do run it, you should see something like the
following:
|
lo
|
Link encap:Local Loopback
inet addr:127.0.0.1 Bcast:127.255.255.255 Mask:255.0.0.0
UP BROADCAST LOOPBACK RUNNING MTU:3584 Metric:1
RX packets:38 errors:0 dropped:0 overruns:0 frame:0
TX packets:38 errors:0 dropped:0 overruns:0 carrier:0
collisions:0
|
|
ppp0
|
Link encap:Point-to-Point Protocol
inet addr:165.247.213.150 P-t-P:168.121.1.1 Mask:255.255.0.0
UP POINTOPOINT RUNNING MTU:1500 Metric:1
RX packets:5 errors:0 dropped:0 overruns:0 frame:0
TX packets:6 errors:0 dropped:0 overruns:0 carrier:0
collisions:0
Memory:8c6418-9f9a04
|
|
My PPP connection to the Internet is called internally ppp0 by
my OS. Were I connected through my Ethernet device, it would be eth0.
Look for something similar.
The two things to look for in this report are the presence of ppp0,
whose absence would indicate I'm not connected, and the numbers
following the term "inet addr."
Let's construct a Perl script that checks to see whether we're on the
Internet and, if so, at what address.
#!/usr/bin/perl
$ip = `/sbin/ifconfig`;
$ip =~ s/(ppp0)(.*)/$2/s;
if (!$1) { print "No connection\n"; }
else {
$ip =~
s/inet addr:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/$1/s;
print "IP is $ip\n";,
}
|
Notice the "back ticks" in the first real line of code. They cause
a command to run, catching its output (which would normally go to
STDOUT) in the variable on the left side of the equation. This would
be 14 lines of output we saw earlier when we ran ifconfig from the
command line.
The next line of code checks for the presence of the "ppp0" string, saving
it, if matched, in the $1 variable. Whatever follows is caught in the $2
variable and becomes all that's left of $ip.
Then it's matter of seeing whether anything was matched by "ppp0." If not,
there is no connection. Otherwise, we know our Internet address is in
what is now in $ip, and that it's comprised of 4 dot-separated sets of
numbers, each from 1 to 3 digits long. We also know that our Internet
address immediately follows the string "inet addr:", so we include that to
ensure we don't get the address of the machine we're connected to.
Using Perl regular expression matching, it's easy to strip the IP address
right out. Next >>
|
|
|