Created
December 23, 2015 20:51
-
-
Save xuecan/490c55ba98f0ef382709 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| # -*- coding: UTF-8 -*- | |
| # Copyright (c) 2015 Netpas Tech-Development Co. Ltd. | |
| import shlex | |
| import ipaddress | |
| DIFF = 10 # 毫秒 | |
| DEFAULT_NETMASK = ipaddress.IPv4Address('255.255.255.0') | |
| def parse_line(line): | |
| """分析一行 | |
| 有效的行形如: 219.141.136.101 (89.1 ms) | |
| 分析后返回 (IPv4Address, int) 2-tuple | |
| """ | |
| segs = shlex.shlex(line) | |
| segs.wordchars += '.' | |
| segs.whitespace += '()' | |
| result = list(segs) | |
| if len(result)!=3 and result[-1]=='ms': | |
| return None | |
| ipaddr = ipaddress.IPv4Address(result[0]) | |
| delay = int(result[1]) | |
| return ipaddr, delay | |
| def _get_network(ipaddr): | |
| network = ipaddress.IPv4Address(int(ipaddr) & int(DEFAULT_NETMASK)) | |
| network = ipaddress.IPv4Network(str(network) + '/' + str(DEFAULT_NETMASK)) | |
| return network | |
| def compare(last, current): | |
| """如果 last 的 IP 地址与 current 的 IP 地址在同一网段, | |
| 且延时相差不超过 DIFF 毫秒,""" | |
| if not last: | |
| return [current] | |
| network = _get_network(last[0]) | |
| if current[0] not in network: | |
| return [last, current] | |
| if abs(current[1]-last[1]) < DIFF: | |
| return [current] | |
| return [last, current] | |
| def parse_file(filename): | |
| last = None | |
| with open(filename, "r", encoding="utf8") as f: | |
| line = f.readline(256) | |
| current = parse_line(line) | |
| if current: | |
| items = compare(last, current) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment