gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:14:20 31 4
gpt4 key购买 nike

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

关于python - 如何根据IP地址整理列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36814392/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com