简体   繁体   中英

sniffing network packets using python

#!/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

I'm trying to capture the packets and there headers Ports & ip address MAC add. but Im getting this error. there is an error to find the port address In TCP header section there is an error

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

Take a look at the output here:

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

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

Now read this:

socket. inet_ntoa(packed_ip)

Convert a 32-bit packed IPv4 address (a string four characters in length) ... ... If the string passed to this function is not exactly 4 bytes in length, socket.error will be raised.

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

But you've written:

sourcePort=socket.inet_ntoa(tcpHdr[0])

...and tcpHdr[0] is equal to '12'. The problem is that '12' is not 4 characters (or 32 bits) long--instead '12' is two characters (or 16 bits) long.

Now, look what happens if you do this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM