专栏名称: Python开发者
人生苦短,我用 Python。伯乐在线旗下账号「Python开发者」分享 Python 相关的技术文章、工具资源、精选课程、热点资讯等。
目录
相关文章推荐
Python开发者  ·  从 3 ... ·  9 小时前  
百职帮  ·  这个暑假学Python,开学直接惊艳所有人!! ·  22 小时前  
百职帮  ·  这个暑假学Python,开学直接惊艳所有人!! ·  22 小时前  
Python开发者  ·  今年IT就业市场的风向已经很明显了。。。 ·  昨天  
Python爱好者社区  ·  确认裁员了,很严重,所有人做好准备吧! ·  3 天前  
Python爱好者社区  ·  python必备手册 ·  4 天前  
51好读  ›  专栏  ›  Python开发者

使用 Python 的 Socket 模块构建一个 UDP 扫描工具

Python开发者  · 公众号  · Python  · 2017-01-20 11:33

正文

请到「今天看啥」查看全文


struct

import ctypes

from ICMPHeader import ICMP

# host to listen on

HOST = '192.168.1.114'

def main () :

socket_protocol = socket . IPPROTO_ICMP

sniffer = socket . socket ( socket . AF_INET , socket . SOCK_RAW , socket_protocol )

sniffer . bind (( HOST , 0 ))

sniffer . setsockopt ( socket . IPPROTO_IP , socket . IP_HDRINCL , 1 )

while 1 :

raw_buffer = sniffer . recvfrom ( 65565 )[ 0 ]

ip_header = raw_buffer [ 0 : 20 ]

iph = struct . unpack ( '!BBHHHBBH4s4s' , ip_header )

# Create our IP structure

version_ihl = iph [ 0 ]

version = version_ihl >> 4

ihl = version_ihl & 0xF

iph_length = ihl * 4

ttl = iph [ 5 ]

protocol = iph [ 6 ]

s_addr = socket . inet_ntoa ( iph [ 8 ]);

d_addr = socket . inet_ntoa ( iph [ 9 ]);

print 'IP -> Version:' + str ( version ) + ', Header Length:' + str ( ihl ) + \

', TTL:' + str ( ttl ) + ', Protocol:' + str ( protocol ) + ', Source:' \

+ str ( s_addr ) + ', Destination:' + str ( d_addr )

# Create our ICMP structure

buf = raw_buffer [ iph_length : iph_length + ctypes . sizeof ( ICMP )]

icmp_header = ICMP ( buf )

print "ICMP -> Type:%d, Code:%d" % ( icmp_header . type , icmp_header . code ) + '\n'

if __name__ == '__main__' :

main ()


测试解码器


在一个终端中运行该脚本,然后在另一个终端运行一个 ping 命令会得到如下结果(注意 ICMP type 值为 0):


$ ping www . google . com

PING www . google . com ( 74.125.226.16 ) 56 ( 84 ) bytes of data .

64 bytes from lga15s42 - in - f16 . 1e100.net ( 74.125.226.16 ) : icmp_seq = 1 ttl = 56







请到「今天看啥」查看全文