Why doesn't the Python socket receive packets? - python

My program doesn't receive any packets (on UDP, Windows 10), but when I sniff the data on Wireshark I can see that the data is indeed sent. I know that it doesn't have anything to do with my local network because when I switch to a hotspot it still doesn't work.
Another thing is that the program receives the data for my friends who work with me on the same project, but for me, even if I'm using the same computer for the client and server it doesn't work.
I even tried to enable Promiscuous in the program via the os module after binding the socket by adding these lines:
if os.name == “nt”:
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
but all I got was
Traceback (most recent call last):
File "C:/Users/roeym/PycharmProjects/client game/tank_trouble_dynamic_map.py", line 5, in <module>
import tank_client
File "C:\Users\roeym\PycharmProjects\client game\tank_client.py", line 13, in <module>
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
OSError: [WinError 10022] An invalid argument was supplied
Can you please help me figure out why my program doesn't receive the data?
This is how I set the socket up:
ip = socket.gethostbyname(socket.gethostname())
port = 8888
s = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
s.bind((ip, port))
print(f"[!][!] Server is up, running on {ip}, port- {port} [!][!]")
and this is how I receive packets:
while run:
data, ip = s.recvfrom(bufferSize)
data = str(data)
data = data[2:]
data = data[:-1]
if data == "":
continue
print(data)

Related

How to recieve data from BT module (HC-05) by using python on Windows 10?

I am trying to receive GPS data from my HC-05 bluetooth module.
I can see complete data in any serial plotter program, however I need to use Python executable for my Raspberry PI.
I have tried below code that I found from internet;
"""
A simple Python script to receive messages from a client over
Bluetooth using PyBluez (with Python 2).
"""
import bluetooth
hostMACAddress = 'C8:09:A8:56:11:EC' # The MAC address of a Bluetooth adapter on the server. The server might have
# multiple Bluetooth adapters.
port = 9
backlog = 1
size = 1024
s = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
s.bind((hostMACAddress, port))
s.listen(backlog)
try:
client, clientInfo = s.accept()
while 1:
data = client.recv(size)
if data:
print(data)
client.send(data) # Echo back to client
except:
print("Closing socket")
client.close()
s.close()
However It gives me error below, for the line "s.bind((hostMACAddress, port))". I have run "ipconfig /all" in cmd window to see bluetooth adapter MAC Adress, and checked advanced settings in "bluetooth devices" of my computer to find corresponding port.
Other problem I suspect is that I am using Python 3.8 while in comment area it says written with Python 2. I am not sure if 3.xx is backward backward compatible with 2.xx.
C:\Users\aliul\PycharmProjects\pythonProject\venv\Scripts\python.exe C:/Users/aliul/PycharmProjects/pythonProject/main.py
Traceback (most recent call last):
File "C:/Users/aliul/PycharmProjects/pythonProject/main.py", line 14, in <module>
s.bind((hostMACAddress, port))
File "C:\Users\aliul\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\bluetooth\msbt.py", line 84, in bind
bt.bind (self._sockfd, addr, port)
OSError: G
I am new to python and any help would be highly appreciated!
Thanks.
I've figured out recieving data importing "serial" package instead of "bluetooth" of pybluez. Source code is below, all you need to do is to find the serial port adress of your socket and setting baudrate, timeout, parity and stopbits parameters according to the bluetooth module you have!
import serial
serialPort = serial.Serial(port='COM8', baudrate=9600, timeout=0, parity=serial.PARITY_EVEN, stopbits=1)
size = 1024
while 1:
data = serialPort.readline(size)
if data:
print(data)

Socket Error in Python: BlockingIOError: [Errno 11] Resource Temporarily Unavailable

So I'm having a problem with the Python Socket module that has completely stumped me. I've searched the internet for answers but nothing seems to work for my case. The problem is this. I'm trying to send data from one a raspberry pi, or a seperate process on my main computer, to my main computer using sockets. When I attempt to do this, I get the error as seen in the title. However, I also have a website that can use the exact same code through an ajax call and it works fine! I really cannot find any difference between the code, it just simply won't work when I execute the exact same code from my Pi or the Python shell.
Server code:
self.ServerSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#Bind socket to local host and port
#pdb.set_trace()
try:
self.ServerSocket.bind((HOST, self.portnum)) # HOST is "", portnum is 8001
except socket.error as msg:
print ("Bind failed. Error Code : ", str(msg))
sys.exit()
#Start listening on socket
while (self.bServerShutdown==False):
# wait to get packet
while True:
# addr is a tupl, so ip = addr[0] port = addr[1]
# Shortened method: data, (ip, port) = self.ServerSocket.recvfrom(1024)
data, addr = self.ServerSocket.recvfrom(1024) # buffer size is 1024 bytes
ip=addr[0]
port=addr[1]
Ajax code (Which works when being called form the website):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = (ipAddress, 8001) # ipAddress = '127.0.0.1' Since site is running on localhost
try:
sent = sock.sendto(Command.encode('utf-8'), server_address)
sock.setblocking(0)
ready = select.select([sock], [], [], 5)
if ready[0]:
data = sock.recv(4096)
#logging.info("received '%s'".format(data))
else:
#logging.info("Timeout")
data=b'Service Manager Timeout. Is it running?\r\n'
except:
continue
'
Code I'm using in the shell (Does not work):
import socket
import select
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = ('127.0.0.1', 8001)
sent = sock.sendto('test command'.encode('utf-8'), server_address)
sock.setblocking(0)
ready = select.select([sock], [], [], 5)
if ready[0]:
data = sock.recv(4096)
else:
data ='timeout'
So to recap, my server code is running. When I navigate to localhost, which is setup to monitor my computer data, everything is good. It makes the ajax call as seen in the second code snippet and data is returned just fine. When I attempt the third code snippet from a Python shell, it returns the error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
BlockingIOError: [Errno 11] Resource temporarily unavailable
So what the heck is going on? Am I missing something really simple or is it something more complicated? Any help would be appreciated.

Simple TCP EchoServer in Python

I found this script of TCP server which "echoes" back the data to the client.
#!/usr/bin/env python
import socket
host = ''
port = 50000
backlog = 5
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(backlog)
while 1:
client, address = s.accept()
data = client.recv(size)
if data:
client.send(data)
client.close()
I'm trying to test & understand it before I will be able to do something on my own and modify, but I'm having some problems. When I'm trying to run the .py script I get the following error in my Terminal (using Ubuntu 14.04 LTS)
> Traceback (most recent call last):
File "echo.py", line 14, in <module>
s.bind((host,port))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in use
My Python version is 2.7.6
is there something wrong with the code or I'm doing something wrong?
UPDATE:
it gets worse, any script I run with bind(host, port) gives me the same error.
any help would be appreciated
Perhaps you accidentally ran the EchoServer twice in different windows? You can only bind one receiver to a port/address combination.
Seems like there is some other application running on those ports.
Can you try checking if there are any other app listening on same port using:
netstat -ntlpu | grep 50000
To bind a server it's a little confusing but you have to use a tuple. The correct way is server.bind((host, port))

Scapy Raw Sockets

I try to implement 3-way-hadnshake with a raw socket in Python and using Scapy.
The code is:
s=socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.IPPROTO_TCP)
ss=StreamSocket(s)
iph=IPheader()
syn = TCP(sport=TCP_SOURCE_PORT,dport=TCP_DESTINATION_PORT, flags="S")
synack = ss.sr1(iph/syn)
myack = iph/TCP(dport=synack[TCP].sport, sport=synack[TCP].dport, seq=synack[TCP].ack, ack=synack[TCP].seq+1, flags="A")
ss.send(myack)
IPheader() method return a scapy IP header.
When running the script i get this error:
ERROR: --- Error in child 3057
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/scapy/sendrecv.py", line 89, in sndrcv
pks.send(p)
File "/usr/lib/python2.7/dist-packages/scapy/supersocket.py", line 34, in send
return self.outs.send(sx)
error: [Errno 6] No such device or address
I see a couple of possible problems with your code:
before invoking StreamSocket() you need to establish a connection with a regular socket. So you need to make a connection, something like s.connect(("10.1.1.1",9000)) before the line ss=StreamSocket(s). Further information can be found here
You may need to correct base socket type. I would suggest something like s=socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP). For further information check this
The device is not responding to your SYN packet because a RAW socket does not do that. You have to send the SYN-ACK manually. Also, Wireshark and TCP show sequence numbers as RELATIVE. In order to show the ACTUAL number you must turn this option off. Thirdly, you can set the sequence number manually or randomize it using
TCP(sport = port1, dport = port2, flags="A", seq = random.getrandbits(32), ack = MY_ACK)
or
TCP(sport = port1, dport = port2, flags="A", seq = 01395, ack = MY_ACK)

Server Client Communication Python

Server
import socket
import sys
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host= 'VAC01.VACLab.com'
port=int(2000)
s.bind((host,port))
s.listen(1)
conn,addr =s.accept()
data=s.recv(100000)
s.close
CLIENT
import socket
import sys
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host="VAC01.VACLab.com"
port=int(2000)
s.connect((host,port))
s.send(str.encode(sys.argv[1]))
s.close()
I want the server to receive the data that client sends.
I get the following error when i try this
CLIENT Side
Traceback (most recent call last):
File "Client.py", line 21, in
s.send(sys.argv[1])
TypeError: 'str' does not support the buffer interface
Server Side
File "Listener.py", line 23, in
data=s.recv(100000)
socket.error: [Errno 10057] A request to send or receive data was disallowed bec
ause the socket is not connected and (when sending on a datagram socket using a
sendto call) no address was supplied
In the server, you use the listening socket to receive data. It is only used to accept new connections.
change to this:
conn,addr =s.accept()
data=conn.recv(100000) # Read from newly accepted socket
conn.close()
s.close()
Your line s.send is expecting to receive a stream object. You are giving it a string. Wrap your string with BytesIO.
Which version of Python are you using? From the error message, I guess you are unintentionally using Python3. You could try your program with Python2 and it should be fine.
try to change the client socket to:
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

Categories