[Tutor] IP Address

Stuart Smith stuart@sharedreality.org
Wed, 22 May 2002 21:18:11 +0100


Here's something I just wrote quickly, it works for uploading my IP to my 
home directory on my web server...

from socket import *
from ftplib import FTP
import os

localip = gethostbyname(gethostname())            # get the local IP address
ipfile = open('myip','w')
ipfile.write(localip)                             # put the IP into a file
ipfile.close()
ipfile = open('myip','r')
ftp = FTP('your.ftpserver.com')                   # open an ftp connection 
to the server
ftp.login('username','password')
ftp.storlines('STOR myip',ipfile)                 # upload the file 
containing the ip
ftp.quit()                                        # disconnect
ipfile.close()
os.remove('myip')                                 # delete the file to tidy up

Not the exact functionality as your shell script, but then i've only really 
been learning Python for a week - I'm unsure of how a machine with multiple 
assigned IP addresses would be handled.


>#!/bin/sh
>
># make a temp file for the address
>TNAME=`tempfile`
>
># extract the first IPv4 address of the interface 'eth0' and store it
># in the temp file
>/sbin/ifconfig eth0 \
>     | grep "inet addr" \
>     | head -1 \
>     | sed 's/.*inet addr:\([[:digit:].]\{7,15}\).*/\1/' \
>     > $TNAME
>
># upload the file
>echo "put $TNAME my_ip" | ftp theserver.com
>
># clean up
>rm -f $TNAME
>
>
>This requires that you put your username and password in ~/.netrc so
>that the ftp program doesn't need to ask you for it.  Obviously change
>the ftp line to use the right server and remote path, and change the
>ifconfig line if you want to publish a different interface's address.
>
>As neat as python is, try writing this program this quickly in it :-).