简体   繁体   English

如何根据IP地址整理列表?

[英]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?是否可以根据解析的 IP 地址对输出进行排序?

You should first generate a list of entries in the form (hostname, ip) for example.例如,您应该首先以(hostname, ip)形式生成条目列表。 After generating that list, iterate over it with sorted() and print out the contents.生成该列表后,使用sorted()对其进行迭代并打印出内容。

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.注意:注意,我正在使用socket.inet_aton将 IPv4 地址从点分四线格式(例如,'123.45.67.89')转换为 32 位压缩二进制格式,作为长度为四个字符的字符串。 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')
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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