generating udp packet using python sockets - python

Can anyone please help on how to fix the following issue:
def __init__(self,source, dest):
self.source = socket.inet_aton(source)
self.dest = socket.inet_aton(dest)
self.sport = 68
self.dport = 67
self.length = 0
self.udpchecksum = 0
self.data = ''
def UDP(self):
udp_hdr = struct.pack('!HHHH', self.sport,
self.dport,
self.length,
self.udpchecksum)
#Pseudo header
psip = self.source
pdip = self.dest
reserved = 0
proto = socket.IPPROTO_UDP
tlen = len(udp_hdr) + len(self.data)
pshdr = struct.pack('!4s4sBBH',
psip,
pdip,
reserved,
proto,
tlen)
pshdr = pshdr + udp_hdr+ self.data
udp_checksum = checksum(pshdr)
udp_hdr = struct.pack('!HHH',
self.sport,
self.dport,
tlen)
udp_checksum = struct.pack('H', udp_checksum)
udp_hdr = udp_hdr + udp_checksum + self.data
return udp_hdr
def checksum(data):
s = 0
n = len(data) % 2
for i in range(0, len(data)-n, 2):
s+= ord(data[i]) + (ord(data[i+1]) << 8)
if n:
s+= ord(data[i+1])
while (s >> 16):
s = (s & 0xFFFF) + (s >> 16)
s = ~s & 0xffff
return s
When I'm sending the packet using raw socket a got an error on wireshark says:
BAD UDP LENGTH
The Question is:
Is it the appropriate way to generate a UDP packet using raw socket ?

Related

How I can make ICMP Pinger code work using python?

I have a problem with running a python code in pox controller...
I have a code that use ping3 to ping between a pox controller and two servers.
However, every time the ping returns (None) as a result and I can't figure out why.
I have tried to go through the code of the icmp pinger and I find out that this line:
whatReady = select.select([mySocket], [], [], timeLeft)
always return this result: [],[],[]
and because of this ping always return (None) instead of numerical number.
The icmp pinger code:
from socket import *
import socket
import os
import sys
import struct
import time
import select
import binascii
ICMP_ECHO_REQUEST = 8
def checksum(str):
csum = 0
countTo = (len(str) / 2) * 2
count = 0
while count < countTo:
thisVal = ord(str[count+1]) * 256 + ord(str[count])
csum = csum + thisVal
csum = csum & 0xffffffffL
count = count + 2
if countTo < len(str):
csum = csum + ord(str[len(str) - 1])
csum = csum & 0xffffffffL
csum = (csum >> 16) + (csum & 0xffff)
csum = csum + (csum >> 16)
answer = ~csum
answer = answer & 0xffff
answer = answer >> 8 | (answer << 8 & 0xff00)
return answer
def receiveOnePing(mySocket, ID, timeout, destAddr):
timeLeft = timeout
while 1:
startedSelect = time.time()
whatReady = select.select([mySocket], [], [], timeLeft)
howLongInSelect = (time.time() - startedSelect)
if whatReady[0] == []: #Timeout
return "Request timed out."
timeReceived = time.time()
recPacket, addr = mySocket.recvfrom(1024)
#Fill in start
#Fetch the ICMP header from the IP packet
ICMPHeader = recPacket[20:28]
Type, Code, Checksum, packetID, Sequence = struct.unpack('bbHHh', ICMPHeader)
if packetID == ID:
BytesInDouble = struct.calcsize('d')
timeSent = struct.unpack('d',recPacket[28:28 + BytesInDouble])[0]
return timeReceived - timeSent
else:
return 'Different ID'
#Fill in end
timeLeft = timeLeft - howLongInSelect
if timeLeft <= 0:
return "Request timed out"
def sendOnePing(mySocket, destAddr, ID):
# Header is type (8), code (8), checksum (16), id (16), sequence (16)
myChecksum = 0
# Make a dummy header with a 0 checksum
# struct -- Interpret strings as packed binary data
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, ID, 1)
data = struct.pack("d", time.time())
# Calculate the checksum on the data and the dummy header.
myChecksum = checksum(header + data)
# Get the right checksum, and put in the header
if sys.platform == 'darwin':
myChecksum = socket.htons(myChecksum) & 0xffff
#Convert 16-bit integers from host to network byte order.
else:
myChecksum = socket.htons(myChecksum)
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, ID, 1)
packet = header + data
mySocket.sendto(packet, (destAddr, 1)) # AF_INET address must be tuple, not str
#Both LISTS and TUPLES consist of a number of objects
#which can be referenced by their position within the object
def doOnePing(destAddr, timeout):
icmp = socket.getprotobyname("icmp")
#SOCK_RAW is a powerful socket type. For more details see: http://sock-raw.ord/papers/sock_raw
#Fill in start
#Create Socket here
try:
mySocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
except socket.error, (errno, msg):
if errno == 1:
raise socket.error(msg)
#Fill in end
myID = os.getpid() & 0xFFFF #Return the current process i
sendOnePing(mySocket, destAddr, myID)
delay = receiveOnePing(mySocket, myID, timeout, destAddr)
mySocket.close()
return delay
ping("www.google.com") # USA - North America
# ping('www.china.org.cn') # China - Asia
# ping('www.thepiratebay.se') # Sweden - Europe
Can anyone help to understand what is the actual problem and how I can fix it...

"Test Failed: unsupported operand type(s) for +: 'int' and 'tuple'"

i keep having a problem in my code coming back as Test Failed: unsupported operand type(s) for +: 'int' and 'tuple'.
i am a super beginner who is not very good at coding, so i cannot figure out what the issue is.
here is the full code.
i am making a simple icmp pinger program.
thanks everyone for your help!!!
(this is my first question here so please let me know if i need to edit anything)
from socket import *
import os
import sys
import struct
import time
import select
import statistics
import binascii
# Should use stdev
ICMP_ECHO_REQUEST = 8
def checksum(string):
csum = 0
countTo = (len(string) // 2) * 2
count = 0
while count < countTo:
thisVal = (string[count + 1]) * 256 + (string[count])
csum += thisVal
csum &= 0xffffffff
count += 2
if countTo < len(string):
csum += (string[len(string) - 1])
csum &= 0xffffffff
csum = (csum >> 16) + (csum & 0xffff)
csum = csum + (csum >> 16)
answer = ~csum
answer = answer & 0xffff
answer = answer >> 8 | (answer << 8 & 0xff00)
return answer
def receiveOnePing(mySocket, ID, timeout, destAddr):
timeLeft = timeout
while 1:
startedSelect = time.time()
whatReady = select.select([mySocket], [], [], timeLeft)
howLongInSelect = (time.time() - startedSelect)
if whatReady[0] == []: # Timeout
return "Request timed out."
timeReceived = time.time()
recPacket, addr = mySocket.recvfrom(1024)
# Fetch the ICMP header from the IP packet
header = recPacket[20:28]
type, code, checksum, packID, seqNo = struct.unpack("bbHHh", header)
if type == 0 and packID == ID:
bytesInDouble = struct.calcsize("d")
timeSent = struct.unpack("d", recPacket[28:28 + bytesInDouble])[0]
ttls = struct.unpack("c", recPacket[8:9])[0]
rtt = timeReceived - timeSent
return (rtt, ttls)
timeLeft = timeLeft - howLongInSelect
if timeLeft <= 0:
return "Request timed out."
def sendOnePing(mySocket, destAddr, ID):
# Header is type (8), code (8), checksum (16), id (16), sequence (16)
myChecksum = 0
# Make a dummy header with a 0 checksum
# struct -- Interpret strings as packed binary data
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, ID, 1)
data = struct.pack("d", time.time())
# Calculate the checksum on the data and the dummy header.
myChecksum = checksum(header + data)
# Get the right checksum, and put in the header
if sys.platform == 'darwin':
# Convert 16-bit integers from host to network byte order
myChecksum = htons(myChecksum) & 0xffff
else:
myChecksum = htons(myChecksum)
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, ID, 1)
packet = header + data
mySocket.sendto(packet, (destAddr, 1)) # AF_INET address must be tuple, not str
# Both LISTS and TUPLES consist of a number of objects
# which can be referenced by their position number within the object.
def doOnePing(destAddr, timeout):
icmp = getprotobyname("icmp")
# SOCK_RAW is a powerful socket type. For more details: http://sockraw.org/papers/sock_raw
mySocket = socket(AF_INET, SOCK_RAW, icmp)
myID = os.getpid() & 0xFFFF # Return the current process i
sendOnePing(mySocket, destAddr, myID)
delay = receiveOnePing(mySocket, myID, timeout, destAddr)
mySocket.close()
return delay
def ping(host, timeout=1):
# timeout=1 means: If one second goes by without a reply from the server, # the client assumes that either the client's ping or the server's pong is lost
dest = gethostbyname(host)
# print("Pinging " + dest + " using Python:")
# print("")
# Calculate vars values and return them
count = 0
val = []
# Send ping requests to a server separated by approximately one second
for i in range(0,4):
delay = doOnePing(dest, timeout)
val.append(delay)
# print(delay)
time.sleep(1) # one second
if len(val) > 0:
packet_min = min(val) * 1000
packet_avg = sum(val) / len(val) * 1000
packet_max = max(val) * 1000
stdev_var = list(val) * 1000
vars = [str(round(packet_min, 2)), str(round(packet_avg, 2)), str(round(packet_max, 2)),str(round(stdev(stdev_var), 2))]
else:
vars = ['0', '0.0', '0', '0.0']
return vars
if __name__ == '__main__':
ping("google.co.il")
You have return (rtt, ttls) in function receiveOnePing and then you return the same tuple from function doOnePing. After that, you append this tuple to list and are trying to sum this list of tuples. This leads to the error you mentioned.
You need val.append(delay[0]) in ping function (line 122).
You also use undefined function stdev. Should be statistics.stdev.
Please note that your script will crash in case of timeout because you return a string in this.
Also the code is runnable only by root.
UPD
Below is fixed code.
rom socket import *
import os
import sys
import struct
import time
import select
import statistics
import binascii
# Should use stdev
ICMP_ECHO_REQUEST = 8
def checksum(string):
csum = 0
countTo = (len(string) // 2) * 2
count = 0
while count < countTo:
thisVal = (string[count + 1]) * 256 + (string[count])
csum += thisVal
csum &= 0xffffffff
count += 2
if countTo < len(string):
csum += (string[len(string) - 1])
csum &= 0xffffffff
csum = (csum >> 16) + (csum & 0xffff)
csum = csum + (csum >> 16)
answer = ~csum
answer = answer & 0xffff
answer = answer >> 8 | (answer << 8 & 0xff00)
return answer
def receiveOnePing(mySocket, ID, timeout, destAddr):
timeLeft = timeout
while 1:
startedSelect = time.time()
whatReady = select.select([mySocket], [], [], timeLeft)
howLongInSelect = (time.time() - startedSelect)
if whatReady[0] == []: # Timeout
return "Request timed out."
timeReceived = time.time()
recPacket, addr = mySocket.recvfrom(1024)
# Fetch the ICMP header from the IP packet
header = recPacket[20:28]
type, code, checksum, packID, seqNo = struct.unpack("bbHHh", header)
if type == 0 and packID == ID:
bytesInDouble = struct.calcsize("d")
timeSent = struct.unpack("d", recPacket[28:28 + bytesInDouble])[0]
ttls = struct.unpack("c", recPacket[8:9])[0]
rtt = timeReceived - timeSent
return (rtt, ttls)
timeLeft = timeLeft - howLongInSelect
if timeLeft <= 0:
return "Request timed out."
def sendOnePing(mySocket, destAddr, ID):
# Header is type (8), code (8), checksum (16), id (16), sequence (16)
myChecksum = 0
# Make a dummy header with a 0 checksum
# struct -- Interpret strings as packed binary data
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, ID, 1)
data = struct.pack("d", time.time())
# Calculate the checksum on the data and the dummy header.
myChecksum = checksum(header + data)
# Get the right checksum, and put in the header
if sys.platform == 'darwin':
# Convert 16-bit integers from host to network byte order
myChecksum = htons(myChecksum) & 0xffff
else:
myChecksum = htons(myChecksum)
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, ID, 1)
packet = header + data
mySocket.sendto(packet, (destAddr, 1)) # AF_INET address must be tuple, not str
# Both LISTS and TUPLES consist of a number of objects
# which can be referenced by their position number within the object.
def doOnePing(destAddr, timeout):
icmp = getprotobyname("icmp")
# SOCK_RAW is a powerful socket type. For more details: http://sockraw.org/papers/sock_raw
mySocket = socket(AF_INET, SOCK_RAW, icmp)
myID = os.getpid() & 0xFFFF # Return the current process i
sendOnePing(mySocket, destAddr, myID)
delay = receiveOnePing(mySocket, myID, timeout, destAddr)
mySocket.close()
return delay
def ping(host, timeout=1):
# timeout=1 means: If one second goes by without a reply from the server, # the client assumes that either the client's ping or the server's pong is lost
dest = gethostbyname(host)
# print("Pinging " + dest + " using Python:")
# print("")
# Calculate vars values and return them
count = 0
val = []
# Send ping requests to a server separated by approximately one second
for i in range(0,4):
delay = doOnePing(dest, timeout)
val.append(delay[0])
# print(delay)
time.sleep(1) # one second
print(val)
if len(val) > 0:
packet_min = min(val) * 1000
packet_avg = sum(val) / len(val) * 1000
packet_max = max(val) * 1000
stdev_var = list(val) * 1000
vars = [str(round(packet_min, 2)), str(round(packet_avg, 2)), str(round(packet_max, 2)),str(round(statistics.stdev(stdev_var), 2))]
else:
vars = ['0', '0.0', '0', '0.0']
return vars
if __name__ == '__main__':
ping("google.co.il")
>sudo python3 ping.py
[0.0778355598449707, 0.07866811752319336, 0.07798004150390625, 0.07628297805786133]
The error occurs in this line:
packet_avg = sum(val) / len(val) * 1000
Therefore val is suspect. Follow the logic back through doOnePing to receiveOnePing and you will find that function does not return suitable types.
You have a few issues. What I can see:
you are trying to checksum but in python, using an index returns a string, not a character, so this generates a string, not a number:
thisVal = (string[count + 1]) * 256 + (string[count])
What you probably want in this case is:
thisVal = ord(string[count + 1]) * 256 + ord(string[count])
and also on this line:
csum += (string[len(string) - 1])
to
csum += ord(string[len(string) - 1])
Then, you are putting tuples and possibly strings into your val array.
You need to decide how you want to handle the errors/time out of the ping.
You could just ignore them for now:
for i in range(0,4):
delay = doOnePing(dest, timeout)
if isinstance(delay, tuple):
val.append(delay[0])
time.sleep(1) # one second
That will only add if you received a tuple, and only add the first member of the tuple, which appears to be the delay you want.

Porting a python 2 code to Python 3: ICMP Scan with errors

import random
import socket
import time
import ipaddress
import struct
from threading import Thread
def checksum(source_string):
sum = 0
count_to = (len(source_string) / 2) * 2
count = 0
while count < count_to:
this_val = ord(source_string[count + 1]) * 256 + ord(source_string[count])
sum = sum + this_val
sum = sum & 0xffffffff
count = count + 2
if count_to < len(source_string):
sum = sum + ord(source_string[len(source_string) - 1])
sum = sum & 0xffffffff
sum = (sum >> 16) + (sum & 0xffff)
sum = sum + (sum >> 16)
answer = ~sum
answer = answer & 0xffff
answer = answer >> 8 | (answer << 8 & 0xff00)
return answer
def create_packet(id):
header = struct.pack('bbHHh', 8, 0, 0, id, 1)
data = 192 * 'Q'
my_checksum = checksum(header + data)
header = struct.pack('bbHHh', 8, 0, socket.htons(my_checksum), id, 1)
return header + data
def ping(addr, timeout=1):
try:
my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
except Exception as e:
print (e)
packet_id = int((id(timeout) * random.random()) % 65535)
packet = create_packet(packet_id)
my_socket.connect((addr, 80))
my_socket.sendall(packet)
my_socket.close()
def rotate(addr, file_name, wait, responses):
print ("Sending Packets", time.strftime("%X %x %Z"))
for ip in addr:
ping(str(ip))
time.sleep(wait)
print ("All packets sent", time.strftime("%X %x %Z"))
print ("Waiting for all responses")
time.sleep(2)
# Stoping listen
global SIGNAL
SIGNAL = False
ping('127.0.0.1') # Final ping to trigger the false signal in listen
print (len(responses), "hosts found!")
print ("Writing File")
hosts = []
for response in sorted(responses):
ip = struct.unpack('BBBB', response)
ip = str(ip[0]) + "." + str(ip[1]) + "." + str(ip[2]) + "." + str(ip[3])
hosts.append(ip)
file = open(file_name, 'w')
file.write(str(hosts))
print ("Done", time.strftime("%X %x %Z"))
def listen(responses):
global SIGNAL
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
s.bind(('', 1))
print ("Listening")
while SIGNAL:
packet = s.recv(1024)[:20][-8:-4]
responses.append(packet)
print ("Stop Listening")
s.close()
SIGNAL = True
responses = []
ips = '200.131.0.0/20' # Internet network
wait = 0.002 # Adjust this based in your bandwidth (Faster link is Lower wait)
file_name = 'log1.txt'
ip_network = ipaddress.ip_network(unicode(ips), strict=False)
t_server = Thread(target=listen, args=[responses])
t_server.start()
t_ping = Thread(target=rotate, args=[ip_network, file_name, wait, responses])
t_ping.start()
I tried:
ip_network = ipaddress.ip_network( ips, strict=False) instead of ip_network = ipaddress.ip_network(unicode(ips), strict=False)
because of the error: ""NameError: name 'unicode' is not defined"
after:
I got: my_checksum = checksum(header + data) -> TypeError: can't concat bytes to str
so I tried:
data = bytes(192 * 'Q').encode('utf8') instead of data = 192 * 'Q'
Now, the error is : ""data = bytes (192 * 'Q').encode('utf8') TypeError: string argument without an encoding"
Could anyone help me to port the code to Python 3 ?
import random
import socket
import time
import ipaddress
import struct
from threading import Thread
def checksum(source_string):
sum = 0
count_to = (len(source_string) / 2) * 2
count = 0
while count < count_to:
this_val = source_string[count + 1] * 256 + source_string[count]
sum = sum + this_val
sum = sum & 0xffffffff
count = count + 2
if count_to < len(source_string):
sum = sum + source_string[len(source_string) - 1]
sum = sum & 0xffffffff
sum = (sum >> 16) + (sum & 0xffff)
sum = sum + (sum >> 16)
answer = ~sum
answer = answer & 0xffff
answer = answer >> 8 | (answer << 8 & 0xff00)
return answer
def create_packet(id):
header = struct.pack('bbHHh', 8, 0, 0, id, 1)
data = 192 * b'Q'
my_checksum = checksum(header + data)
header = struct.pack('bbHHh', 8, 0, socket.htons(my_checksum), id, 1)
return header + data
def ping(addr, timeout=1):
try:
my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
except Exception as e:
print (e)
packet_id = int((id(timeout) * random.random()) % 65535)
packet = create_packet(packet_id)
my_socket.connect((addr, 80))
my_socket.sendall(packet)
my_socket.close()
def rotate(addr, file_name, wait, responses):
print ("Sending Packets", time.strftime("%X %x %Z"))
for ip in addr:
ping(str(ip))
time.sleep(wait)
print ("All packets sent", time.strftime("%X %x %Z"))
print ("Waiting for all responses")
time.sleep(2)
# Stoping listen
global SIGNAL
SIGNAL = False
ping('127.0.0.1') # Final ping to trigger the false signal in listen
print (len(responses), "hosts found!")
print ("Writing File")
hosts = set()
for response in sorted(responses):
ip = struct.unpack('BBBB', response)
ip = str(ip[0]) + "." + str(ip[1]) + "." + str(ip[2]) + "." + str(ip[3])
hosts.add(ip)
with open(file_name, 'w') as file:
file.write('\n'.join(sorted(hosts, key=lambda item: socket.inet_aton(item))))
print ("Done", time.strftime("%X %x %Z"))
def listen(responses):
global SIGNAL
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
s.bind(('', 1))
print ("Listening")
while SIGNAL:
packet = s.recv(1024)[:20][-8:-4]
responses.append(packet)
print ("Stop Listening")
s.close()
SIGNAL = True
responses = []
ips = '192.168.1.0/28' # Internet network
wait = 0.002 # Adjust this based in your bandwidth (Faster link is Lower wait)
file_name = 'log1.txt'
ip_network = ipaddress.ip_network(ips, strict=False)
t_server = Thread(target=listen, args=[responses])
t_server.start()
t_ping = Thread(target=rotate, args=[ip_network, file_name, wait, responses])
t_ping.start()

Python packet sniffer problems running

I created a python code that is meant to be a basic packet sniffer. The code compiles however when it runs it gives no errors but there is no output either. My main question is what went wrong with the code. Open to suggestions. I have used IDLE and coderunner on OS X to attempt to get a running program.
Here is what I have so far thanks.
import socket
import struct
import textwrap
TAB_1 = '\t - '
TAB_2 = '\t\t - '
TAB_3 = '\t\t\t - '
TAB_4 = '\t\t\t\t - '
DATA_TAB_1 = '\t '
DATA_TAB_2 = '\t\t '
DATA_TAB_3 = '\t\t\t '
DATA_TAB_4 = '\t\t\t\t '
def main():
pcap = Pcap('capture.pcap')
conn = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(3))
while True:
raw_data, addr = conn.recvfrom(65535)
pcap.write(raw_data)
eth = Ethernet(raw_data)
print('\nEthernet Frame:')
print(TAB_1 + 'Destination: {}, Source: {}, Protocol: {}'.format(eth.dest_mac, eth.src_mac, eth.proto))
# IPv4
if eth.proto == 8:
ipv4 = IPv4(eth.data)
print(TAB_1 + 'IPv4 Packet:')
print(TAB_2 + 'Version: {}, Header Length: {}, TTL: {},'.format(ipv4.version, ipv4.header_length, ipv4.ttl))
print(TAB_2 + 'Protocol: {}, Source: {}, Target: {}'.format(ipv4.proto, ipv4.src, ipv4.target))
# ICMP
if ipv4.proto == 1:
icmp = ICMP(ipv4.data)
print(TAB_1 + 'ICMP Packet:')
print(TAB_2 + 'Type: {}, Code: {}, Checksum: {},'.format(icmp.type, icmp.code, icmp.checksum))
print(TAB_2 + 'ICMP Data:')
print(format_multi_line(DATA_TAB_3, icmp.data))
# TCP
elif ipv4.proto == 6:
tcp = TCP(ipv4.data)
print(TAB_1 + 'TCP Segment:')
print(TAB_2 + 'Source Port: {}, Destination Port: {}'.format(tcp.src_port, tcp.dest_port))
print(TAB_2 + 'Sequence: {}, Acknowledgment: {}'.format(tcp.sequence, tcp.acknowledgment))
print(TAB_2 + 'Flags:')
print(TAB_3 + 'URG: {}, ACK: {}, PSH: {}'.format(tcp.flag_urg, tcp.flag_ack, tcp.flag_psh))
print(TAB_3 + 'RST: {}, SYN: {}, FIN:{}'.format(tcp.flag_rst, tcp.flag_syn, tcp.flag_fin))
if len(tcp.data) > 0:
# HTTP
if tcp.src_port == 80 or tcp.dest_port == 80:
print(TAB_2 + 'HTTP Data:')
try:
http = HTTP(tcp.data)
http_info = str(http.data).split('\n')
for line in http_info:
print(DATA_TAB_3 + str(line))
except:
print(format_multi_line(DATA_TAB_3, tcp.data))
else:
print(TAB_2 + 'TCP Data:')
print(format_multi_line(DATA_TAB_3, tcp.data))
# UDP
elif ipv4.proto == 17:
udp = UDP(ipv4.data)
print(TAB_1 + 'UDP Segment:')
print(TAB_2 + 'Source Port: {}, Destination Port: {}, Length: {}'.format(udp.src_port, udp.dest_port, udp.size))
# Other IPv4
else:
print(TAB_1 + 'Other IPv4 Data:')
print(format_multi_line(DATA_TAB_2, ipv4.data))
else:
print('Ethernet Data:')
print(format_multi_line(DATA_TAB_1, eth.data))
# Returns MAC as string from bytes (ie AA:BB:CC:DD:EE:FF)
def get_mac_addr(mac_raw):
byte_str = map('{:02x}'.format, mac_raw)
mac_addr = ':'.join(byte_str).upper()
return mac_addr
def ipv4_packet(self, raw_data):
version_header_length = raw_data[0]
self.version = version_header_length >> 4
self.header_length = (version_header_length & 15) * 4
self.ttl, self.proto, src, target = struct.unpack('! 8x B B 2x 4s 4s', raw_data[:20])
self.src = self.ipv4(src)
self.target = self.ipv4(target)
self.data = raw_data[self.header_length:]
# Returns properly formatted IPv4 address
def ipv4(self, addr):
return '.'.join(map(str, addr))
def icmp_packet(self, raw_data):
self.type, self.code, self.checksum = struct.unpack('! B B H', raw_data[:4])
self.data = raw_data[4:]
def tcp_segment(self, raw_data):
(self.src_port, self.dest_port, self.sequence, self.acknowledgment, offset_reserved_flags) = struct.unpack(
'! H H L L H', raw_data[:14])
offset = (offset_reserved_flags >> 12) * 4
self.flag_urg = (offset_reserved_flags & 32) >> 5
self.flag_ack = (offset_reserved_flags & 16) >> 4
self.flag_psh = (offset_reserved_flags & 8) >> 3
self.flag_rst = (offset_reserved_flags & 4) >> 2
self.flag_syn = (offset_reserved_flags & 2) >> 1
self.flag_fin = offset_reserved_flags & 1
self.data = raw_data[offset:]
def udp_segment(self, raw_data):
self.src_port, self.dest_port, self.size = struct.unpack('! H H 2x H', raw_data[:8])
self.data = raw_data[8:]
# Formats multi-line data
def format_multi_line(prefix, string, size=80):
size -= len(prefix)
if isinstance(string, bytes):
string = ''.join(r'\x{:02x}'.format(byte) for byte in string)
if size % 2:
size -= 1
return '\n'.join([prefix + line for line in textwrap.wrap(string, size)])
curiosity... thenewboston
I have used IDLE and coderunner on OS X to attempt to get a running program.
...
conn = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(3))
That's not going to work on OS X; OS X doesn't have AF_PACKET as an address family. I'm surprised your program didn't fail with an exception.
If you're going to capture packet traffic, you should use pcap; you're already using it to write the capture file, you should use it to capture packets. It will use the OS's mechanism (BPF, on OS X, *BSD, AIX, and Solaris 11; AF_PACKET sockets on Linux; etc.) to capture packets.

Python TypeError: 'int' object has no attribute '__getitem__'

import bluetooth
import time
class btHandler():
hostMACAddress = '98:D3:31:30:45:80'
port = 1
gyro = [None]
rot = [None]
data = 0
def __init__(self):
self.clientSocket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
self.clientSocket.connect((self.hostMACAddress, self.port))
self.clientSocket.setblocking(True)
def testRead(self):
self.gyro = [None] * 3
global data
d = self.clientSocket.recv(1)
d = ord(d[0])
if d == 0x25:
d = self.clientSocket.recv(1)
d = ord(d[0])
if d == 0x72:
time.sleep(0.02)
self.data = self.clientSocket.recv(28)
if len(self.data)<28:
print "Wrong data lenght", len(self.data)
else:
self.gyro[0] = ord(self.data[0]) * 256 + ord(self.data[1])
print self.gyro[0]
return self.gyro[0]
def getGyroValues(self):
self.rot = [None] * 3
self.rot[0] = ord(self.data[10]) * 256 + ord(self.data[11])
print rot[1];
This is my code and I'm getting error at line 37 (self.rot[0] = ord(self.data[10]) * 256 + ord(self.data[11]) )
What my program do is read data microcontroller using bluetooth.
__getitem__ is indexing, so check your code to see if you have done an index operation ([]) on an int in your code, and fix it.

Categories

Resources