I am testing some scripts, and i found a null error traceback on the client script:
=========== RESTART: /home/pi/Desktop/Pythonic/Chat/ReadClient.py ===========
Enter name: SuperUser
Enter server port: 5162
> Traceback (most recent call last):
I have no idea what this means, and here are both the scripts:
What i am thinking is, the python default IDE thinks it found an error, but it does not recognize this error type. So it returns a null traceback.
Client script
import os, threading
from socket import *
name = input('Enter name: ')
bufsiz = 1024
host = 'localhost'
port = int(input('Enter server port: '))
addr = (host, port)
client = socket(AF_INET , SOCK_STREAM)
##try:
client.connect(addr)
##except socket_error as serr:
## if serr.errno != errno.ECONNREFUSED:
## raise serr
## else:
## print('Invalid Port number:[111]')
## port = int(input('Enter server port: '))
## addr = (host, port)
## client.connect(addr)
# sending name
client.sendto(name.encode('utf-8'),addr)
os.system('cls' if os.name == 'nt' else 'clear')
def input_loop():
global data, client
while True:
data = input('> ')
if not data:
client.sendto('/disconnect'.encode('utf-8'),addr)
break
else:
client.sendto(data.encode('utf-8'),addr)
def recv_loop(client,caddr):
while True:
data = client.recv(1024).decode('utf-8')
if data != 'n_dat':
if data != '/ping':
print(data)
else:
client.sendto('/ping'.encode('utf-8'),caddr)
print('pinged by server')
threads = []
dat_thread = threading.Thread(target=input_loop, args=())
dat_thread.start()
thread = threading.Thread(target=recv_loop, args=(client,caddr))
thread.start()
Server Script:
import os, socket, time, threading, random
class Server:
def __init__(self,host,port,user):
self.port = port
self.host = host
self.user = user
self.bufsize = 1024
self.addr = (host,port)
self.socket = socket.socket(socket.AF_INET , socket.SOCK_STREAM)
self.socket.bind(self.addr)
print("Server running on",host,"at port",port)
self.socket.listen(5)
class rank:
def __init__(self, level):
self.level = level
def getPerms(l):
return (l==6,l>=6,True,l>=3,l>=2,l>=5,l>=4,l>=3,l>=2,l>=5>l>=6)
def getPerms(level,action):
return getperms(level)[action]
def getLevel(level):
if(level == 1):
return 'Guest'
if(level == 2):
return 'Experienced'
if(level == 3):
return 'Veteran'
if(level == 4):
return 'Donor'
if(level == 5):
return 'Mod'
if(level == 6):
return 'Admin'
if(level == 7):
return 'Owner'
else:
return False
# level scale
# A = Server control
# B = Ban
# C = Chat
# D = Direct Message
# H = Vanish
# I = ignore
# K = Kick
# M = Server mute
# T = Title
# V = View members
# U = Unban
## A B C D I K M T V H U
## _____________________________________
## 1 | Guest | | |X| | | | | | | | |
## 2 | Experienced | | |X| |X| | | |X| | |
## 3 | Veteran | | |X|X|X| | |X|X| | |
## 4 | Donor | | |X|X|X| |X|X|X|X| |
## 5 | Mod | | |X|X|X|X|X|X|X|X| |
## 6 | Admin | |X|X|X|X|X|X|X|X|X|X|
## 7 | Owner |X|X|X|X|X|X|X|X|X|X|X|
## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def recv_loop(server,client,caddr):
print ('Connected To',caddr)
while True:
global clients
global ping_count
name = clients[client]
data = client.recv(1024)
namecheck = getrank(caddr[0],name,)
formattime = time.strftime(time.strftime("%H:%M:%S",time.gmtime()))
if not data:
break
if data.decode('utf-8') == '/disconnect':
print(formattime + ' : ' +'[' + namecheck + ']'+ name +' has disconnected ')
break
if data.decode('utf-8') == '/ping':
pings = 0
mssg = str(formattime + ' : ' +'[' + namecheck + ']'+ name +': '+ data.decode('utf-8'))
print(formattime + ' : ' +'[' + namecheck + ']'+ name +': '+ data.decode('utf-8'))
for c in clients:
if c != client:
c.send(mssg.encode('utf-8'))
else:
c.send(bytes('n_dat','utf-8'))
log(name, data.decode('utf-8'),getrank(caddr[0],name))
client.close()
def log(name, msg, rank):
with open('log.txt', 'a') as log:
log.write(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime())+ ' ' + name + ': ' + msg + '\n')
def getrank(ip, name):
with open('ranks.txt', 'r') as ranks:
for line in ranks:
addr = line.split('$',1)[0]
if addr == ip:
rank = (line.split('$$',1)[0]).split('$')[1]
return rank
print('new user')
writerank(ip,name)
return ' Guest '
def writerank(ip,name):
with open('ranks.txt','a') as file:
file.write(ip + '$' + ' Guest ' + '$$' + name + '$$$' + '0/n')
def ping(client, ping_rate):
global ping_count
while True:
time.sleep(60/ping_rate)
client.send(bytes('/ping','utf-8'))
print('pinging client ' + str(client))
ping_count = ping_count + 1
##def getname(caddr):
## with open('ranks.txt', 'r+') as ranks:
## for line in ranks:
## addr = line.split(' .R. ')[0]
## if addr == caddr:
## name = line.split(' ... ')[1]
## return bytes(name,'utf-8')
##
host = 'localhost'
port = random.randint(5000,6000)
user = 'No one'
name = input('Server name : ')
ping_rate = 6
server = Server(host, port, user)
clients = {}
threads = []
ping_count = 0
while True:
client, caddr = server.socket.accept()
# name extraction
name = client.recv(1024)
#name = getname(caddr)
clients[client] = name.decode('utf-8')
pingthread = threading.Thread(target=ping, args=(client,ping_rate))
thread = threading.Thread(target=recv_loop, args=(server,client, caddr))
pingthread.start()
thread.start()
Does anyone know why this null trackback is occurring??
And if so, How is it avoided?
I seem to have found the answer:
> Traceback (most recent call last):Hello\
> File "/home/pi/Desktop/Pythonic/Chat/ReadClient.py", line 58, in <module>
thread = threading.Thread(target=recv_loop, args=(client,caddr))
Uhh
> NameError: name 'caddr' is not defined
So, as it turns out, the traceback is three separate print functions, but as i have an input loop going, it delayed the print until the input is satisfied
How to reproduce:
import threading
def InputThread():
global data
while True:
data = input('> ')
inputThread = thread.Thread(target=InputThread,args=())
inputThread.start()
raise Exception
Related
I'm trying to complete the mininet topology exercise from this website https://github.com/mininet/openflow-tutorial/wiki/Advanced-Topology.
Basically I have to create a topology like this:
h1-----s1---s2----h3
(there is also another host attached to s1 called h2)
and program a POX controller to install flows to the switches so that the pingall and iperf commands work.
Everything works fine except for the iperf command which fails when it runs from h1 to h3 or from h2 to h3.
This is the code I have, and I believe the problem has to do with communicating to the right switch what to do with packets of a type different than arp or icmp, but I've been stuck too long on this problem and have decided to ask for help here.
from pox.core import core
import pox.openflow.libopenflow_01 as of
import pox.lib.packet as pkt #ipv4, arp..
import pox.lib.addresses as adr #EthAddr , IPAddr ..
log = core.getLogger()
class Tutorial (object):
def __init__ (self, connection):
# Keep track of the connection to the switch so that we can
# send it messages!
self.connection = connection
# This binds our PacketIn event listener
connection.addListeners(self)
self.dpid_table = {'10.0.1.1': 1, '10.0.2.1': 2}
# Use this table to keep track of which ethernet address is on
# which switch port (keys are MACs, values are ports).
self.ip_to_port = {'10.0.1.2':1, '10.0.1.3':2, '10.0.2.2':3}
self.mac_to_port = {}
self.routing_table = {
'10.0.1.0/24': [['10.0.1.2', 's1-eth1', '10.0.1.1', 1, '00:00:00:00:00:01'],
['10.0.1.3', 's1-eth2', '10.0.1.1', 2, '00:00:00:00:00:02']],
'10.0.2.0/24': ['10.0.2.2', 's2-eth1', '10.0.2.1', 3, '00:00:00:00:00:03'],
}
def FlowMode(self, packet_in, out_port):
print("Creating Flow...")
msg = of.ofp_flow_mod()
msg.match.in_port = packet_in.in_port
#msg_match = of.ofp_match(dl_type = pkt.ethernet.IP_TYPE, nw_proto = pkt.ipv4.IPv4)
msg.idle_timeout = 15
msg.buffer_id = packet_in.buffer_id
action = of.ofp_action_output(port = out_port)
msg.actions.append(action)
self.connection.send(msg)
print("flow created")
def act_like_router (self, packet, packet_in):
#handle ARP Requests and replies
etherPayload = packet.payload #the stripped ethFrame, contains ipv4 or arp packet
if packet.type == pkt.ethernet.ARP_TYPE:
#etherPayload is an ARP packet
src_ip = etherPayload.protosrc
dst_ip = etherPayload.protodst
if etherPayload.opcode == pkt.arp.REQUEST:
print("ARP REQUEST received by controller....\n Constructing reply...")
arp_reply = pkt.arp()
arp_reply.hwsrc = adr.EthAddr("11:12:13:14:15:16") #fake mac in response
arp_reply.hwdst = etherPayload.hwsrc
arp_reply.opcode = pkt.arp.REPLY
arp_reply.protosrc = etherPayload.protodst
arp_reply.protodst = etherPayload.protosrc
#encapsulate in ethernet frame now
ether = pkt.ethernet()
ether.type = pkt.ethernet.ARP_TYPE
ether.dst = packet.src
ether.src = packet.dst
ether.payload = arp_reply
msg = of.ofp_packet_out()
msg.data = ether.pack()
action = of.ofp_action_output(port = packet_in.in_port)
msg.actions.append(action)
self.connection.send(msg)
#send to switch, will have to implement flow instead
#self.resend_packet(ether, packet_in.in_port)
print("ARP Reply sent!")
elif etherPayload.opcode == pkt.arp.REPLY:
if src_ip not in self.arp_table:
self.arp_table[str(src_ip)] = etherPayload.hwsrc
self.mac_to_port[etherPayload.hwsrc] = packet_in.in_port
print("ARP REPLY received by controller updating tables")
print(self.mac_to_port)
print(self.arp_table)
#else:
#self.mac_to_port[etherPayload.hwsrc] = packet_in.in_port
else:
print("some other ARP OPCODE received")
elif packet.type == pkt.ethernet.IP_TYPE:
#etherPayload is an IP packet
if etherPayload.protocol == pkt.ipv4.ICMP_PROTOCOL:
icmp_packet = etherPayload.payload
if icmp_packet.type == pkt.TYPE_ECHO_REQUEST:
print("received ping request...\n creating echo_reply message")
src_ip = etherPayload.srcip
dst_ip = etherPayload.dstip
k = 0
#check if destination exist in any of the subnets
for subnet in self.routing_table.keys():
if dst_ip.inNetwork(subnet): #possible mistake here maybe turn dst_ip into IPADDR obj
k = subnet
break
if k!=0:
#host exists create and send echo reply
print('Sending reply to network ' + str(k))
#create echo fields
ech = pkt.echo() #echo contained in pkt.icmp
ech.id = icmp_packet.payload.id
ech.seq = icmp_packet.payload.seq + 1
#encapsulates in icmp
icmp_reply = pkt.icmp()
icmp_reply.type = pkt.TYPE_ECHO_REPLY #code 0
icmp_reply.payload = ech
#encapsulates in ipv4
ip_p = pkt.ipv4()
ip_p.protocol = pkt.ipv4.ICMP_PROTOCOL
ip_p.srcip = dst_ip
ip_p.dstip = src_ip
ip_p.payload = icmp_reply
#encapsulates in ethernet
eth_p = pkt.ethernet()
eth_p.type = pkt.ethernet.IP_TYPE
eth_p.src = packet.dst
eth_p.dst = packet.src
eth_p.payload = ip_p
msg = of.ofp_packet_out()
msg.data = eth_p.pack()
action = of.ofp_action_output(port = packet_in.in_port)
print("sending reply from: " + str(dst_ip) + " to: " + str(src_ip) + " using packet_in.in_port: " + str(packet_in.in_port))
msg.actions.append(action)
self.connection.send(msg)
#send to switch, will have to implement flow instead
#self.resend_packet(eth_p, packet_in.in_port)
print("echo Reply sent!")
else:
#host doesn't exist send dst unreachable
print("ICMP destination unreachable")
unr = pkt.unreach()
unr.payload = etherPayload
icmp_reply = pkt.icmp()
icmp_reply.type = pkt.TYPE_DEST_UNREACH
icmp_reply.payload = unr
ip_p = pkt.ipv4()
ip_p.srcip = dst_ip
ip_p.dstip = src_ip
ip_p.protocol = pkt.ipv4.ICMP_PROTOCOL
ip_p.payload = icmp_reply
eth_p = pkt.ethernet()
eth_p.type = pkt.ethernet.IP_TYPE
eth_p.dst = packet.src
eth_p.src = packet.dst
eth_p.payload = ip_p
msg = of.ofp_packet_out()
msg.data = eth_p.pack()
action = of.ofp_action_output(port = packet_in.in_port)
#print("sending reply from: " + str(dst_ip) + " to: " + str(src_ip) + " using packet_in.in_port: " + str(packet_in.in_port))
msg.actions.append(action)
self.connection.send(msg)
#send to switch, will have to implement flow instead
#self.resend_packet(eth_p, packet_in.in_port)
log.debug("echo Reply sent!")
#se non e` ICMP
else:
print("received some ip packet...\n handling it... ")
src_ip = etherPayload.srcip
dst_ip = etherPayload.dstip
k = 0
#check if destination exist in any of the subnets
'''
self.routing_table = {
'10.0.1.0/24': ['10.0.1.2', 's1-eth1', '10.0.1.1', 1, '00:00:00:00:00:02'],
['10.0.1.3', 's1-eth2', '10.0.1.1', 2, '00:00:00:00:00:03']
'''
for subnet in self.routing_table.keys():
if dst_ip.inNetwork(subnet):
k = subnet
break
if k!=0:
port1 = self.ip_to_port[str(dst_ip)] #get port to communicate on that subnet
if str(dst_ip) == '10.0.1.2':
#ethDest = adr.EthAddr("4e:2d:32:b9:bc:52")
ethDest = adr.EthAddr(self.routing_table[subnet][0][4])
msg = of.ofp_packet_out()
action = of.ofp_action_output(port = port1)
packet.src = packet.dst
packet.dst = ethDest#adr.EthAddr('11:11:11:11:11:11')#ethDest
msg.data = packet.pack()
msg.actions.append(action)
self.connection.send(msg)
print("installing flow for packets for: " + str(dst_ip))
self.FlowMode(packet_in, packet_in.in_port)
elif str(dst_ip) == '10.0.1.3':
#ethDest = adr.EthAddr("22:02:eb:9c:27:2d")
ethDest = adr.EthAddr(self.routing_table[subnet][1][4])
msg = of.ofp_packet_out()
action = of.ofp_action_output(port = port1)
packet.src = packet.dst
packet.dst = ethDest#adr.EthAddr('11:11:11:11:11:11')#ethDest
msg.data = packet.pack()
msg.actions.append(action)
self.connection.send(msg)
print("installing flow for packets for: " + str(dst_ip))
self.FlowMode(packet_in, packet_in.in_port)
elif str(dst_ip) == '10.0.2.2':
ethDest = adr.EthAddr(self.routing_table[subnet][4])
if packet_in.in_port == 1 and self.connection.dpid == 1:
outport = 3
msg = of.ofp_packet_out()
action = of.ofp_action_output(port = outport)
packet.src = packet.dst
packet.dst = ethDest
msg.data = packet.pack()
msg.actions.append(action)
self.connection.send(msg)
print("installing flow for packets for: " + str(dst_ip) + " to switch number: " + str(connection.dpid)
+ str(etherPayload.id))
self.FlowMode(packet_in, packet_in.in_port)
elif (packet_in.in_port == 2 or packet_in.in_port == 3) and self.connection.dpid == 1:
outport = 1
msg = of.ofp_packet_out()
action = of.ofp_action_output(port = outport)
packet.src = packet.dst
packet.dst = ethDest
msg.data = packet.pack()
msg.actions.append(action)
self.connection.send(msg)
print("installing flow for packets for: " + str(dst_ip) + " to switch number: " + str(self.connection.dpid)
+ str(etherPayload.id))
self.FlowMode(packet_in, packet_in.in_port)
elif packet_in.in_port == 1 and self.connection.dpid == 2:
outport = 3
msg = of.ofp_packet_out()
action = of.ofp_action_output(port = outport)
packet.src = packet.dst
packet.dst = ethDest
msg.data = packet.pack()
msg.actions.append(action)
self.connection.send(msg)
print("installing flow for packets for: " + str(dst_ip) + " to switch number: " + str(self.connection.dpid)
+ str(etherPayload.id))
self.FlowMode(packet_in, packet_in.in_port)
elif(packet_in.in_port == 2 or packet_in.in_port == 3) and self.connection.dpid == 2:
outport = 1
msg = of.ofp_packet_out()
action = of.ofp_action_output(port = outport)
packet.src = packet.dst
packet.dst = ethDest
msg.data = packet.pack()
msg.actions.append(action)
self.connection.send(msg)
print("installing flow for packets for: " + str(dst_ip) + " to switch number: " + str(self.connection.dpid)
+ str(etherPayload.id))
self.FlowMode(packet_in, packet_in.in_port)
'''
router_msg = of.ofp_flow_mod()
router_msg.match = of.ofp_match.from_packet(packet)
router_msg.idle_timeout = 100
router_msg.buffer_id = packet_in.buffer_id
action = of.ofp_action_output(port = packet_in.in_port)
router_msg.actions.append(action)
self.connection.send(router_msg)
'''
#don't forget flow mode
def _handle_PacketIn (self, event):
"""
Handles packet in messages from the switch.
"""
packet = event.parsed # This is the ethernet packet.
if not packet.parsed:
log.warning("Ignoring incomplete packet")
return
packet_in = event.ofp # The actual ofp_packet_in message.
self.act_like_router(packet, packet_in)
def resend_packet(self, packet_in, out_port):
"""
Instructs the switch to resend a packet that it had sent to us.
"packet_in" is the ofp_packet_in object the switch had sent to the
controller due to a table-miss.
"""
msg = of.ofp_packet_out()
msg.data = packet_in.pack()
# Add an action to send to the specified port
action = of.ofp_action_output(port=out_port)
msg.actions.append(action)
# Send message to switch
self.connection.send(msg)
def launch ():
"""
Starts the component
"""
def start_switch (event):
log.debug("Controlling %s" % (event.connection,))
Tutorial(event.connection)
core.openflow.addListenerByName("ConnectionUp", start_switch)
EDIT:
I solved this by flooding IP_packets directed to h3, to all ports except the in_port
I have successful sending and receiving between test_client and test_server for a few sends and receives. But when I input more than 4 or 5 data and click enter after each at the input() function the program hangs. I think I've narrowed the problem down to likely be either the rdt_rcv() or udt_send() function. I've highlighted with comments the rdt_rcv() function for both sender and receiver and added a comment above the udt_send() function. But I can't see what's wrong with the functions. Of course it could be something else but I think the problem is one of the two functions I mentioned above. Try running the programs by running test_server first and test_client second with rdt.py in the same folder as the 2 test modules.
test_client.py
import socket, rdt, sys
TCP_IP = 'localhost'
TCP_PORT = 10000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
InitialSeqNumber = 0
NextSeqNum = InitialSeqNumber
SendBase = InitialSeqNumber
while 1:
d = input("Input data: ")
data = rdt.rdt_send(d)
data = int(data)
if rdt.rdt_send_called == 1:
checksum = 0xFFFF - data # Assuming 28 byte data
sndpkt = rdt.packet(NextSeqNum, 0, checksum, data)
rdt.udt_send(sndpkt, s)
NextSeqNum = NextSeqNum + sys.getsizeof(data)
#####################################
seq, ack, check, dat = rdt.rdt_rcv(s)
#####################################
rdt.rdt_send_called = 0
print ("Sequence Number: " + str(seq))
print ("ACK Number: " + str(ack))
print ("Checksum Value: " + hex(check))
print ("Data: " + str(dat))
print ('\n')
s.close()
rdt.py
rdt_send_called = None
timeout_event = None
ACK_received = None
BUFFER_SIZE = 1024
class packet:
def __init__(self, seq_num, ack_num, checksum, data):
self.seq_num = seq_num
self.ack_num = ack_num
self.checksum = checksum
self.data = data
def rdt_send(data):
d = data
global rdt_send_called
rdt_send_called = 1
return d
# PROBLEM MAY BE WITH THIS FUNCTION
def udt_send(sndpkt, s):
s.send((str(sndpkt.seq_num)).encode())
s.send((str(sndpkt.ack_num)).encode())
s.send((str(sndpkt.checksum)).encode())
s.send((str(sndpkt.data)).encode())
# PROBLEM IS MOST LIKELY WITH THIS FUNCTION
def rdt_rcv(conn):
field1 = conn.recv(BUFFER_SIZE)
field1 = int(field1)
field2 = conn.recv(BUFFER_SIZE)
field2 = int(field2)
#if field2 != 0:
#global ACK_received
#ACK_received = 1
field3 = (conn.recv(BUFFER_SIZE))
field3 = int(field3)
field4 = (conn.recv(BUFFER_SIZE))
field4 = int(field4)
return field1, field2, field3, field4
def deliver_data(data):
pass
def timeout():
global timeout_event
timeout_event = 1
test_server.py
import socket, rdt, sys
TCP_IP = '127.0.0.1'
TCP_PORT = 10000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
while 1:
dont_send_ACK = 0
#####################################################
seq_num, ack_num, check_sum, data = rdt.rdt_rcv(conn)
#####################################################
print ("Sequence Number: " + str(seq_num))
print ("ACK number: " + str(ack_num))
print ("Checksum Value: " + hex(check_sum))
print ("Data: " + hex(data))
print ('\n')
if data + check_sum != 0xFFFF:
dont_send_ACK = 1 # sender will timeout
else:
rdt.deliver_data(data)
if dont_send_ACK == 0:
ACK = seq_num + sys.getsizeof(data)
checksum = 0xFFFF - ACK
sndpkt = rdt.packet(0, ACK, checksum, 0)
rdt.udt_send(sndpkt, conn)
conn.close()
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()
I am using for loop to get the mac address from database but the loop printed the ble mac address 17 times. I tried using if else to compare the mac address with the mac address stored in database but the output scan nothing. Is there any other way to filter out other ble mac address?
import os
import sys
import struct
import bluetooth._bluetooth as bluez
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","DB_USER","DB_PASSWORD","DB_NAME" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
sql = "SELECT * FROM Mac_address"
cursor.execute(sql)
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
for row in results:
NAME = row[0]
mac_address = row[1]
time = row[2]
LE_META_EVENT = 0x3e
LE_PUBLIC_ADDRESS=0x00
LE_RANDOM_ADDRESS=0x01
LE_SET_SCAN_PARAMETERS_CP_SIZE=7
OGF_LE_CTL=0x08
OCF_LE_SET_SCAN_PARAMETERS=0x000B
OCF_LE_SET_SCAN_ENABLE=0x000C
OCF_LE_CREATE_CONN=0x000D
LE_ROLE_MASTER = 0x00
LE_ROLE_SLAVE = 0x01
# these are actually subevents of LE_META_EVENT
EVT_LE_CONN_COMPLETE=0x01
EVT_LE_ADVERTISING_REPORT=0x02
EVT_LE_CONN_UPDATE_COMPLETE=0x03
EVT_LE_READ_REMOTE_USED_FEATURES_COMPLETE=0x04
# Advertisment event types
ADV_IND=0x00
ADV_DIRECT_IND=0x01
ADV_SCAN_IND=0x02
ADV_NONCONN_IND=0x03
ADV_SCAN_RSP=0x04
def returnnumberpacket(pkt):
myInteger = 0
multiple = 256
for c in pkt:
myInteger += struct.unpack("B",c)[0] * multiple
multiple = 1
return myInteger
def returnstringpacket(pkt):
myString = "";
for c in pkt:
myString += "%02x" %struct.unpack("B",c)[0]
return myString
def printpacket(pkt):
for c in pkt:
sys.stdout.write("%02x " % struct.unpack("B",c)[0])
def get_packed_bdaddr(bdaddr_string):
packable_addr = []
addr = bdaddr_string.split(':')
addr.reverse()
for b in addr:
packable_addr.append(int(b, 16))
return struct.pack("<BBBBBB", *packable_addr)
def packed_bdaddr_to_string(bdaddr_packed):
return ':'.join('%02x'%i for i in struct.unpack("<BBBBBB", bdaddr_packed[::-1]))
def hci_enable_le_scan(sock):
hci_toggle_le_scan(sock, 0x01)
def hci_disable_le_scan(sock):
hci_toggle_le_scan(sock, 0x00)
def hci_toggle_le_scan(sock, enable)
cmd_pkt = struct.pack("<BB", enable, 0x00)
bluez.hci_send_cmd(sock, OGF_LE_CTL, OCF_LE_SET_SCAN_ENABLE, cmd_pkt)
def hci_le_set_scan_parameters(sock):
old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14)
SCAN_RANDOM = 0x01
OWN_TYPE = SCAN_RANDOM
SCAN_TYPE = 0x01
def parse_events(sock, loop_count=100):
old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14)
# perform a device inquiry on bluetooth device #0
# The inquiry should last 8 * 1.28 = 10.24 seconds
# before the inquiry is performed, bluez should flush its cache of
# previously discovered devices
flt = bluez.hci_filter_new()
bluez.hci_filter_all_events(flt)
bluez.hci_filter_set_ptype(flt, bluez.HCI_EVENT_PKT)
sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, flt )
done = False
results = []
myFullList = []
for i in range(0, loop_count):
pkt = sock.recv(255)
ptype, event, plen = struct.unpack("BBB", pkt[:3])
#print "--------------"
if event == bluez.EVT_INQUIRY_RESULT_WITH_RSSI:
i =0
elif event == bluez.EVT_NUM_COMP_PKTS:
i =0
elif event == bluez.EVT_DISCONN_COMPLETE:
i =0
elif event == LE_META_EVENT:
subevent, = struct.unpack("B", pkt[3])
pkt = pkt[4:]
if subevent == EVT_LE_CONN_COMPLETE:
le_handle_connection_complete(pkt)
elif subevent == EVT_LE_ADVERTISING_REPORT:
#print "advertising report"
num_reports = struct.unpack("B", pkt[0])[0]
report_pkt_offset = 0
for i in range(0, num_reports):
Mac = packed_bdaddr_to_string(pkt[report_pkt_offset + 3:report_pkt_offset + 9])
for Mac in row[1]:
print "-------------"
#print "\tfullpacket: ", printpacket(pkt)
print "\tMAC address: ", row[1] # commented out - don't know what this byte is. It's NOT TXPower
txpower, = struct.unpack("b", pkt[report_pkt_offset -2])
print "\t(Unknown):", txpower
rssi, = struct.unpack("b", pkt[report_pkt_offset -1])
print "\tRSSI:", rssi
break
# build the return string
Adstring = packed_bdaddr_to_string(pkt[report_pkt_offset + 3:report_pkt_offset + 9])
Adstring += ","
Adstring += returnstringpacket(pkt[report_pkt_offset -22: report_pkt_offset - 6])
Adstring += ","
Adstring += "%i" % returnnumberpacket(pkt[report_pkt_offset -6: report_pkt_offset - 4])
Adstring += ","
Adstring += "%i" % returnnumberpacket(pkt[report_pkt_offset -4: report_pkt_offset - 2])
Adstring += ","
Adstring += "%i" % struct.unpack("b", pkt[report_pkt_offset -2])
Adstring += ","
Adstring += "%i" % struct.unpack("b", pkt[report_pkt_offset -1])
#print "\tAdstring=", Adstring
myFullList.append(Adstring)
done = True
sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, old_filter )
return myFullList
db.close()
The above is save as blescan.py. I run this file below to do a ble scan.
import blescan
import sys
import bluetooth._bluetooth as bluez
dev_id = 0
try:
sock = bluez.hci_open_dev(dev_id)
print "ble thread started"
except:
print "error accessing bluetooth device..."
sys.exit(1)
blescan.hci_le_set_scan_parameters(sock)
blescan.hci_enable_le_scan(sock)
while True:
returnedList = blescan.parse_events(sock, 10)
print "----------"
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.