Skip to main content
 首页 » 编程设计

python之如何根据IP地址整理列表

2024年10月24日9zdz8207

#!/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,' ')) 

输出如下

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 

是否可以根据解析的IP地址对输出进行整理?

请您参考如下方法:

尝试:

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.

例如

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])) 

将输出:

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