使用python嗅探网络数据包

时间:2015-01-11 10:16:33

标签: python sockets

#!/usr/bin/env python
import struct
import sys,os
import socket
import binascii

rawSocket=socket.socket(socket.PF_PACKET,socket.SOCK_RAW,socket.htons(0x0800))
#ifconfig eth0 promisc up
receivedPacket=rawSocket.recv(2048)

#Ethernet Header...
ethernetHeader=receivedPacket[0:14]
ethrheader=struct.unpack("!6s6s2s",ethernetHeader)
destinationIP= binascii.hexlify(ethrheader[0])
sourceIP= binascii.hexlify(ethrheader[1])
protocol= binascii.hexlify(ethrheader[2])

print "Destination: " + destinationIP
print "Source: " + sourceIP
print "Protocol: "+ protocol

#IP Header... 
ipHeader=receivedPacket[14:34]
ipHdr=struct.unpack("!12s4s4s",ipHeader)
destinationIP=socket.inet_ntoa(ipHdr[2])
sourceIP=socket.inet_ntoa(ipHdr[1])
print "Source IP: " +sourceIP
print "Destination IP: "+destinationIP

#TCP Header...
tcpHeader=receivedPacket[34:54]
tcpHdr=struct.unpack("!2s2s16s",tcpHeader)
sourcePort=socket.inet_ntoa(tcpHdr[0])
destinationPort=socket.inet_ntoa(tcpHdr[1])
print "Source Port: " + sourcePort
print "Destination Port: " + destinationPort

我试图捕获数据包并且有标题端口& ip address MAC add。但我得到这个错误。 找到端口地址时出错 在TCP标题部分 有错误

Traceback (most recent call last):
  File "sniff.py", line 33, in <module>
    sourcePort=socket.inet_ntoa(tcpHdr[0])
socket.error: packed IP wrong length for inet_ntoa

1 个答案:

答案 0 :(得分:1)

看看这里的输出:

x = struct.pack('!2s2s16s', '12', '34', '5678901234567890')
tcpHdr=struct.unpack("!2s2s16s", x)
print tcpHdr
print tcpHdr[0]

--output:--
('12', '34', '5678901234567890')
12

现在阅读:

  

插座。的 INET_NTOA(packed_ip)

     

转换32位打包的IPv4地址(字符串中的四个字符)   长度)   ...   ...   如果传递给此函数的字符串长度不是4个字节,则将引发socket.error。

https://docs.python.org/2.7/library/socket.html#socket.inet_ntoa

但是你已经写过:

sourcePort=socket.inet_ntoa(tcpHdr[0])

...和tcpHdr [0]等于&#39; 12&#39;。问题在于&#39; 12&#39; 12不是4个字符(或32位)长 - 而是&#39; 12&#39;是两个字符(或16位)长。

现在,看看如果你这样做会发生什么:

import struct
import socket

x = struct.pack('!4s4s12s', '1234', '5678', '901234567890')
tcpHdr=struct.unpack("!4s4s12s", x)

print tcpHdr
print tcpHdr[0]

print socket.inet_ntoa(tcpHdr[0]) #===> NO ERROR

--output:--
('1234', '5678', '901234567890')
1234
49.50.51.52