Python Socket Programming ConnectionRefusedError: [Errno 61] Connection refused - python-3.x

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.

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.

psycopg2 connects from Windows, but not Ubuntu

My Postgres database only accepts requests from localhost. Requests from a remote computer rely on SSH tunnel.
with SSHTunnelForwarder(
('my.db.ip.address', 22),
ssh_username='ssh_user_name',
ssh_private_key='id_rsa.pem',
remote_bind_address=('127.0.0.1', 5432)) as server:
conn = psycopg2.connect(database="my_db", port=server.local_bind_port, user=id, password=pwd)
curs = conn.cursor()
sql = "select t.id from public.my_table t"
This code works from Windows machine. On Ubuntu it fails with
File "/home/me/projects/compliance/response_generator.py", line 22, in get_rows
conn = psycopg2.connect(database="my_db", port=server.local_bind_port, user=id,password=pwd)
File "/home/me/anaconda3/envs/my_env/lib/python3.8/site-packages/psycopg2/__init__.py", line 122, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: connection to server on socket "/tmp/.s.PGSQL.38945" failed: No such file or directory
Is the server running locally and accepting connections on that socket?
What could be the reason and how to fix it?
----Update-----
tunnel = SSHTunnelForwarder(
('my.db.ip.address', 22),
ssh_username='ssh_user_name',
ssh_private_key='exdtras.dat',
remote_bind_address=('localhost', 5432),
local_bind_address=('localhost',6543), # could be any available port
Returns raise ValueError('No password or public key available!') ValueError: No password or public key available!
Any idea why this code works on Windows, but fails on Ubuntu?

ESP32 Socket client not connecting to python server

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! 🎉

Don't understand why server won't respond to client (even after turning of firewall | Python | Server

I set up my server on MacBook air and my client is connecting from a Windows 10 machine. I turned off all security and firewalls on both machines (because that's what you do when you've lost all hope) and tried to connect from my windows machine multiple times, but to no avail. I'm on the same network btw (not using a VM).
Error:
TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
Server:
import socket, threading
import multiprocessing
from time import sleep
# tells us the bytes of the message
HEADER = 64
PORT = 5430
# or you could do socket.gethostbyname(socket.gethostname())
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = '!END'
# defines the type of connection
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
def start():
server.listen()
print(f'[LISTENING] Server is listening on {SERVER}')
while True:
conn, addr = server.accept()
print('[ACTIVE CONNECTIONS] 1')
start()
Client:
from time import sleep
import socket, subprocess
HEADER = 64
PORT = 5430
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = '!END'
SERVER = '192.32.322.3'
ADDR = (SERVER, PORT)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDR)

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.

Resources