[Tutor] Want to write a Perl based IP to Domain Name converter.

Martin Walsh mwalsh at mwalsh.org
Sun Feb 1 04:36:35 CET 2009


wesley chun wrote:
>>>>> The script in the following can do the batch conversion from domain
>>>>> name to IP:
>>>>  This is a Python list, not Perl!
>>> OMG!  It's my mistake, sorry for this.
>> Lol..thats okay. Now that you are here and have seen what fun we have
>> writing Python code - why not join the party?
>>
>> Don't be shy to join us :p - i bet you won't be sorry.
> 
> 
> well, he had to join Tutor to post, unless a mod allowed his msg, so
> there should be *some* interest in doing it in Python. after all, the
> equivalent code is already slightly shorter and easier to read than
> the Perl version...
> 
> import socket
> import sys
> 
> for hp in sys.argv[1:]:
>     h, p = hp.strip().split(':')
>     print '%s -> %s:%s' % (hp, socket.gethostbyname(h), p)


Here's my attempt, a few lines longer. The 'split /:/ or next' part
confuses me a bit, though I suspect it's a bug ... 'cause I guess, as
long as the line has value even if it doesn't match the host:port
pattern, it won't be an exception, or undef, or false, or whatever you
call it in perl. :D

import socket
import fileinput

for line in fileinput.input():
    line = line.rstrip('\n') # chomp
    try: # split /:/
        host, port = line.split(':')
    except ValueError:
        continue # or next
    ip = socket.gethostbyname(host)
    print '%s -> %s:%s' % (line, ip, port)

... and the opposite ...

for line in fileinput.input():
    line = line.rstrip('\n')
    try:
        ip, port = line.split(':')
    except ValueError:
        continue
    host = socket.gethostbyaddr(ip)[0]
    print '%s -> %s:%s' % (line, host, port)

HTH,
Marty


More information about the Tutor mailing list