java怎么对ip地址排序,如何用端口号对IP地址排序?

I am creating my own reporting tool, and I am trying to figure out how to sort IP address with port number.

How do I sort an IP address with port number such that I sort the IP address first and then through port number. I am able to sort IP address just fine, but when combining with port numbers, it becomes difficult.

a = ['192.168.0.3 (443/tcp)|', '192.168.0.176 (443/tcp)|', '192.168.0.40 (443/tcp)|', '192.168.0.15 (8443/tcp)|', '192.168.0.16 (8443/tcp)|', '192.168.0.12 (443/tcp)|', '192.168.0.9 (3389/tcp)|', '192.168.0.15 (443/tcp)|', '192.168.0.16 (443/tcp)|', '192.168.0.3 (3389/tcp)|', '192.168.0.14 (443/tcp)|']

print(a.sort(key=lambda s: map(int, s.split('.')))) #this works fine with just IP address not with the current format of (xxx/tcp). The pipe is for delimiters so please ignore.

I would like to get the output sorted by IP address first, and then for each IP to sort via port number. So for example, the first few results would be:

a= ['192.168.0.3 (443/tcp)|', '192.168.0.3 (3389/tcp)|', 192.168.0.9 (3389/tcp)|, ...']

解决方案

Using re.findall:

import re

def get_ip_port(x):

*ips, port = map(int, re.findall('\d+', x))

return ips, port

sorted(a, key=get_ip_port)

Output:

['192.168.0.3 (443/tcp)|',

'192.168.0.3 (3389/tcp)|',

'192.168.0.9 (3389/tcp)|',

'192.168.0.12 (443/tcp)|',

'192.168.0.14 (443/tcp)|',

'192.168.0.15 (443/tcp)|',

'192.168.0.15 (8443/tcp)|',

'192.168.0.16 (443/tcp)|',

'192.168.0.16 (8443/tcp)|',

'192.168.0.40 (443/tcp)|',

'192.168.0.176 (443/tcp)|']

Explanation:

map(int, re.findall('\d+', x)): finds all digits and make them int

*ips, port: unpacks the above ints and repack into all but last one (*ips) and last one (port)

sorted(a, key=get_ip_port): as get_ip_port returns two keys (ips,port), sorted sorts the a first by ips and then port, just as desired.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值