简体   繁体   中英

How can I get the list sorted out according to the IP address?

#!/usr/bin/python
# -*- encoding:utf8 -*-

import sys
import fileinput
import socket

hostlist= ['www.yahoo.com','www.google.com', 'www.facebook.com', 'www.cnn.com', 'www.thetimes.com']

for line in hostlist:
    for hostnames in line.split():
        try:
            socket.gethostbyname(hostnames)
        except Exception as invalid_hostnames:
            print ('Invalid hostname address = ') + hostnames
        else:
            ip = socket.gethostbyname(hostnames)
            print (ip.ljust(30,' ')) + '' + (hostnames.ljust(30,' '))

the output comes as below

46.228.47.115                 www.yahoo.com                 
123.176.0.162                 www.google.com                
179.60.192.36                 www.facebook.com              
185.31.17.73                  www.cnn.com                   
54.229.184.19                 www.thetimes.com

Would it be possible to get the output sorted out according to the resolved IP address?

You should first generate a list of entries in the form (hostname, ip) for example. After generating that list, iterate over it with sorted() and print out the contents.

For example, instead of the print, make a list:

 result = []

And append your entries to that list instead of printing them out:

result.append((hostname, ip))

Then, after processing all items, print them out sorted:

for hostname, ip in sorted(result, key=lambda v: v[1]):
    print (ip.ljust(30,' ')) + '' + (hostnames.ljust(30,' '))

Try:

import socket

results = []

with open('hostnames_list.txt') as f:
    for hostname in f:
        try:
            ip = socket.gethostbyname(hostname.strip())
        except socket.gaierror:
            ip = socket.gethostbyname('.'.join(hostname.strip().split('.')[1:]))
        results.append((ip, hostname.strip()))

for (ip, hostname) in sorted(results, key=lambda item: socket.inet_aton(item[0])):
    print (ip.ljust(30,' ')) + '' + (hostname.ljust(30,' '))

Note: See that I'm using socket.inet_aton to convert an IPv4 address from dotted-quad string format (for example, '123.45.67.89') to 32-bit packed binary format, as a string four characters in length. This way, you'll have them sorted correctly.

Eg

data = [
        ('31.13.73.36', 'google.com'),
        ('31.13.72.35', 'foo.bar'),
        ('31.13.72.36', 'somedomain.com')
]
print sorted(data, key=lambda item: socket.inet_aton(item[0]))

Will output:

[
    ('31.13.72.35', 'foo.bar'),
    ('31.13.72.36', 'somedomain.com'),
    ('31.13.73.36', 'google.com')
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM