ESP32 Socket client not connecting to python server - python-3.x

Hey!
Am a developer trying to establish a socket connection between my pc and an esp32 connected on the same network.
Code
On esp32(micropython)
import usocket
import network
def do_connect():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('connecting to network...')
wlan.connect('whydoesnt', 'itwork')
while not wlan.isconnected():
pass
print('network config:', wlan.ifconfig())
def connect_socket():
addr = ("192.168.1.4", 80)
s = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)
s.connect(addr)
s.send("hello")
s.close()
do_connect()
connect_socket()
On my computer (python3.9)
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("0.0.0.0", 80))
s.listen(3)
while True:
client, addr = s.accept()
print("Connected by {}".format(addr))
while True:
content = client.recv(32)
if len(content) == 0:
break
else:
print(content)
print("Closing connection")
client.close()
Am hosting the socket server on 0.0.0.0 so that it runs on the wifi network.
Well, the python server works. I tested it using puTTy running on the same pc. I just had to get my ip address from cmd and connect to it using putty.
Error
But, when I tried doing the same with the esp32, it didn't work, and gave me this error:
network config: ('192.168.1.10', '255.255.255.0', '192.168.1.1', '192.168.1.1')
Traceback (most recent call last):
File "<stdin>", line 24, in <module>
File "<stdin>", line 19, in connect_socket
OSError: [Errno 113] ECONNABORTED
Well, thank you in advance! 🎉

Related

How to route TCP traffic through Tor proxy?

I would like to create a TCP connection using python library socket. This traffic should be redirected through Tor network but socks.SOCKS5Error: 0x01: General SOCKS server failure is given.
The code below can connect to Tor proxy and gives a new Tor IP.
from stem.control import Controller
from stem import Signal
import socket
import socks
if __name__ == "__main__":
with Controller.from_port(port=9051) as controller:
# Creatting TOR connection
controller.authenticate(password='password')
controller.signal(Signal.NEWNYM)
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "192.168.1.148", 9050)
socket.socket = socks.socksocket
# Creatting socket connection
new_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '192.168.1.148'
port = 50007
new_socket.connect((host, port))
new_socket.sendall('Hello world')
print(new_socket.recv(1024))
This is the error given:
Traceback (most recent call last):
File "/usr/lib/python3.10/site-packages/socks.py", line 809, in connect
negotiate(self, dest_addr, dest_port)
File "/usr/lib/python3.10/site-packages/socks.py", line 443, in _negotiate_SOCKS5
self.proxy_peername, self.proxy_sockname = self._SOCKS5_request(
File "/usr/lib/python3.10/site-packages/socks.py", line 533, in _SOCKS5_request
raise SOCKS5Error("{:#04x}: {}".format(status, error))
socks.SOCKS5Error: 0x01: General SOCKS server failure
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/pi/keylogger-project/./tor_proxy_connection.py", line 74, in <module>
tor.__testing_socket_availability__()
File "/home/pi/keylogger-project/./tor_proxy_connection.py", line 66, in __testing_socket_availability__
self.socket.connect((host, port))
File "/usr/lib/python3.10/site-packages/socks.py", line 47, in wrapper
return function(*args, **kwargs)
File "/usr/lib/python3.10/site-packages/socks.py", line 814, in connect
raise GeneralProxyError("Socket error", error)
socks.GeneralProxyError: Socket error: 0x01: General SOCKS server failure
Server side is a simple nc -lvp 50007
Regards
socket.socket = socks.socksocket
...
host = '192.168.1.148'
...
new_socket.connect((host, port))
The target 192.168.1.148 is an IP address reserved for private networks and thus not reachable from the internet. But the nodes on the Tor network are on the internet and thus cannot reach the given target.

OSError: [Errno 22] Invalid argument for udp connection

The udp server and client on my local pc.
cat server.py
import socket
MAX_BYTES =65535
def server():
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sock.bind(('127.0.0.1',10000))
print('Listening at {}'.format(sock.getsockname()))
while True:
data,address = sock.recvfrom(MAX_BYTES)
text = data.decode('ascii')
print('The client at {} says {!r} '.format(address,text))
if __name__ == "__main__":
server()
Bind port 10000 with localhost-127.0.0.1,and listening to the message send from client.
cat client.py
import socket
import time
from datetime import datetime
MAX_BYTES =65535
def client():
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sock.bind(('127.0.0.1',10001))
text = 'The time is {}'.format(datetime.now())
data = text.encode('ascii')
while True:
time.sleep(10)
sock.sendto(data,('127.0.0.1',10000))
print('The OS assinged me the address {}'.format(sock.getsockname()))
if __name__ == "__main__":
client()
Run the server.py and client.py on my local pc,server can receive message send from client.
Now i change 127.0.0.1 in the line in client.py with my remote vps_ip.
sock.sendto(data,('127.0.0.1',10000))
into
sock.sendto(data,('remote_ip',10000))
Push server.py into my vps.Start client.py on my local pc,server.py on remote vps,start them all.
In my client,an error info occurs:
File "client.py", line 13, in client
sock.sendto(data,('remote_ip',10000))
OSError: [Errno 22] Invalid argument
How to make remote ip receive message send from my local client pc?
Two things that could be happening:
You're not passing the remote IP correctly. Make sure that your not passing literally 'remote_ip' and replace it with a valid IPv4 IP address string (IE: '192.168.0.100') for the server. (FYI technically on the server you can just put '0.0.0.0' to listen on all IP addresses)
You could still be binding the client to the local address to (127.0.0.1), but setting the destination to a valid external address (192.168.0.100). Remove the socket.bind line of code in the client to test this, you shouldn't need it.
If these both don't work, then add the results of a ping command running on the client and targeting the server.

catch socket timeout error

i want to catch socket.timeout error, here is my code:
import socket
import sys
from time import sleep
print("Server Listening...")
IPparse = "localhost"
Portparse = 4444
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = (IPparse, Portparse)
serverSocket.settimeout(5)
serverSocket.bind(server_address)
serverSocket.listen(2)
(server, (ip,port)) = serverSocket.accept()
try:
data = server.recv(16).decode()
if data == "Hello":
print("Hallo Bro")
except socket.timeout as e:
print ("Timeout is over")
print (e)
but when i running that code. i got this error:
Server Listening...
Traceback (most recent call last):
File "C:\Users\astend\Desktop\TA\20180220 - Gabungan Gui - v.1\Socket\terima2.py", line 13, in <module>
(server, (ip,port)) = serverSocket.accept()
File "C:\Users\astend\AppData\Local\Programs\Python\Python36\lib\socket.py", line 205, in accept
fd, addr = self._accept()
socket.timeout: timed out
What key point am I missing here?
You need to do the accept() inside the try block.
Or else don't set the timeout on the listening socket, set it on the accepted sockets.

Python Socket Programming ConnectionRefusedError: [Errno 61] Connection refused

This is my code for the server program:
import socket
soket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
HOST = "localhost"
PORT = 8011
soket.bind((HOST,PORT))
print("%s:%d server başlatıldı." % (HOST,PORT))
print("Kullanıcı bekleniyor.")
soket.listen(2)
baglanti,adres = soket.accept()
print("Bir bağlantı kabul edildi.", adres)
baglanti.send("Hoşgeldiniz efendim , hoşgeldiniz.")
data = baglanti.recv(1024)
print(data)
soket.close()
And this is for the client:
import socket
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(("localhost", 8011))
clientsocket.send('hello')
Although I first start the server program and then the client program, I get this error:
Traceback (most recent call last):
File "/Users/Esat/Desktop/Python/Softwares/socketto copy.py", line 3, in <module>
clientsocket.connect(("localhost", 8011))
ConnectionRefusedError: [Errno 61] Connection refused
Instead of localhost, it is better to use LAN (local) IP. You can get your local IP by running ipconfig (in Windows) or ifconfig (in GNU/Linux or Mac OS). Your local IP should be something like 192.168.1.x.

python 3 tcp server and client string transfer error

I try to develop a simple server and client program, I run the code with python 3.4.2.( on Debian 8.6 ) . The server run well, the client program connect's to the server but when I pass a text in terminal to send to server and send back with time stamp, I get this error in the client terminal window
Traceback (most recent call last):
File "tcp_client", line 15, in
tcpCliSock.send(data)
TypeError: 'str' does not support the buffer interface
this is the server code
from socket import *
from time import ctime
HOST = '192.168.0.141'
PORT = 21577
BUFSIZ = 1024
ADDR = (HOST, PORT)
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)
while True:
print('waiting for connection...')
tcpCliSock, addr = tcpSerSock.accept()
print('....connected from :', addr)
while True:
data = tcpCliSock.recv(BUFSIZ)
if not data:
break
tcpCliSock.send('[%s] %s' % (bytes(ctime(), 'utf-8'), data))
tcpCliSock.close()
tcpSerSock.close()
and this it the client code
from socket import *
HOST = '192.168.0.141'
PORT = 21577
BUFSIZ = 1024
ADDR = (HOST, PORT)
tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
while True:
data = input('> ')
if not data:
break
tcpCliSock.send(data)
data = tcpCliSock.recv(BUFSIZ)
if not data:
break
print(data.decode('utf-8'))
tcpCliSock.close()

Resources