Python | Connecting to a remote server using sockets - python

recently I've been messing around with sockets in python and i needed to connect to a remote server for a project. I know there are plenty of questions about this topic but none of the solutions worked for me and i am about to go mad if i can't get this to work.
Server code:
import socket
import threading
FORMAT = "UTF-8"
PORT = 55555
SERVER = ''
ADDR = ('0.0.0.0', PORT)
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
def handle_client(conn, addr):
print(f"[NEW CONNECTION] {addr} connected.")
conn.send("Test".encode(FORMAT))
def start():
server.listen()
print(f"[LISTENING] Server is listening on {PORT}")
while True:
connection, adress = server.accept()
thread = threading.Thread(target=handle_client, args=(connection, adress))
thread.start()
print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}")
print("[STARTING] server is starting...")
start()
Client Code:
import socket
import threading
FORMAT = "UTF-8"
PORT = 55555
SERVER = "xx.xxx.xxx.xxx" # public ip
print(f"\nconnecting... {PORT}\n")
ADDR = (SERVER, PORT)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
client.connect(ADDR)
except:
print("Couldnt connect.")
print(client.recv(1024).decode(FORMAT))
When i change the SERVER variable in client script to my local ip (192.168.1.34), i can run these two scripts in two different pcs in the same LAN and it works well, i recieve the "Test" message in my client pc.
However, when i change the SERVER variable to my public ip and run the server in my server pc, i can't connect to the client pc. Here, my server and client pcs are NOT in the same network. Server is connected to my router whereas client is in another network. When i run the client script nothing happens and after a while i get [WINERROR 10057]
I've done port forwarding to port 55555. I tried disabling all firewalls and even creating a new rule in windows firewall to allow connections from port 55555. It still doesn't work and i can't figure out why.
If there is anyone who can see the problem here i would really appreciate it.

The only thing I can see that maybe is causing a problem is in your ADDR variable. I recently did a similar project that was successful, and in my sever code I did the equivalent of:
ADDR('',PORT)
I don't know for sure this would fix your problem, but it is my best guess from the info you provided.

Related

Python Socket Server Isn't Accepting Connections From Outside The Local WIFI Network

I created a simple messaging app and I'm trying to make it so people outside my home network can join. I port forwarded the machine its running on. I made sure that the Iv4 and port match the settings on the Xfinity gateway. Even then its still not working outside my Home network. Is there something else I have to do to make it work?
Here is the server code. Don't know if it helps though.
import threading
import socket
host = "IV4 HERE"
port = PORT HERE
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen()
clients = []
nicknames = []
def brodcast(message):
for client in clients:
client.send(message)
def handle(client):
while True:
try:
message = client.recv(1024)
brodcast(message)
except:
index = clients.index(client)
clients.remove(client)
client.close()
nickname = nicknames[index]
brodcast(f'''
{nickname} left the chat'''.encode('ascii'))
nicknames.remove(nickname)
break
def recive():
while True:
client, address = server.accept()
print(f"Connected with {str(address)}")
client.send('NICK'.encode('ascii'))
nickname = client.recv(1024).decode('ascii')
nicknames.append(nickname)
clients.append(client)
print(f'{nickname} joined the chat!')
brodcast(f'{nickname} joined the chat!'.encode('ascii'))
client.send('Connected to the chat'.encode('ascii'))
thread = threading.Thread(target=handle, args=(client,))
thread.start()
recive()
Probably not the answer you are looking for. But tunnels can help you out here.
I learned about them from this video by Fireship.
https://www.youtube.com/watch?v=SlBOpNLFUC0
Here's a summary of the steps:
Use CloudFlare Tunnels or Ngrok
download the cloudflare tunnel cli tool
run the tunnel command and point it to the localhost port you want to serve
it will spit out a url where now anybody can view your localhost on the internet

Python socket connection not working over Local Network

I'm trying to get two computers (my PC and my laptop) to communicate over the Local Network using the Socket module in python.
This is the Server side code running on my PC (connected via LAN):
import socket
HOST = '192.168.1.3' #local PC IP
print(HOST)
PORT = 8080 # Port to listen on (non-privileged ports are > 1023)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
print(data)
if not data:
break
conn.sendall(data)
And this is the Client side code, running on my Laptop (connected over WiFi):
import socket
TCP_IP = '192.168.1.3'
TCP_PORT = 8080
BUFFER_SIZE = 1024
MESSAGE = b"Hello, World!"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(MESSAGE)
data = s.recv(BUFFER_SIZE)
s.close()
print("received data:", data)
The thing is: when I execute both codes, the Server side stays idle waiting for a connection and the Client side, after a while stops and returns the following timeout error:
Traceback (most recent call last):
File "C:\Users\...\client.py", line 13, in <module>
s.connect((TCP_IP, TCP_PORT))
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
I can't understand why it won't connect from another device in the same network while it works perfectly if I execute the Client code on the same machine as the Server, even if when I run netstat -an in the CMD I can see the computer listening on that port:
TCP 192.168.1.3:8080 0.0.0.0:0 LISTENING
I tough it had something to do with the port forwarding so I tried playing around with it but I'm having troubles with that too (the ports seem to remain closed).
I really don't know what to do next, if you have some advice or know something else I could try please reply.
It actually was a firewall problem, I just needed to disable the windows defender firewall for the local network and now everything is working fine
In Windows 10, I had to open the port I was using for the socket, and it worked for me.
Here is a link to the instructions.
You're listening and connecting to the same IP - you need to listen to the client's IP(or just any IP with the correct port number) on the server and connect to the server's IP on the client.
For example, if the client's IP is 1.2.3.4 and the server's is 1.2.3.5, then
# server side
s.bind(('1.2.3.4', 8080)) # CLIENT_IP = '1.2.3.4'; PORT = 8080
# can also be s.bind(('0.0.0.0', 8080)) if you want multiple clients to connect.
# client side
s.connect(('1.2.3.5', 8080)) # SERVER_IP = '1.2.3.5'; PORT = 8080

Online Python sockets

I am trying to make a simple app in Python with sockets, but clients only receive the message "Test" sent from the server if they're in the LAN. I tried to run the client (the server is running on my PC) from my laptop and from my PC. In both cases I received the message "Test", but when a friend tries to connect he doesn't receive the message.
Here is my server.py:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 7908))
s.listen(5)
while True:
clientsocket, address = s.accept()
print(f"Connection from {address} established")
clientsocket.send(bytes("Test", "utf-8"))
And here is my client.py:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("my_public_ip_address", 7908))
print(s.recv(8).decode("utf-8"))
I compile client.py with pyinstaller before sending it, so that the script can run without Python being installed on the machine (I don't even have Python on my laptop)
Thanks for taking the time to read and awnsering this :) (Sorry if my english is bad, I'm french)
I guess your friend is outside your LAN: if so you should open/portforward port 7908 on the router to the server.
Open port 7908 on the sever PC firewall.
Your script in this way should work.

Socket server in python refuses to connect

I am trying to create a simple web server with python using the following code.
However, When I run this code, I face this error:
ConnectionRefusedError: [WinError 10061] No connection could be made
because the target machine actively refused it
It worths mentioning that I have already tried some solutions suggesting manipulation of proxy settings in internet options. I have run the code both in the unticked and the confirmed situation of the proxy server and yet cannot resolve the issue.
Could you please guide me through this ?
import sys
import socketserver
import socket
hostname = socket.gethostname()
print("This is the host name: " + hostname)
port_number = 60000
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
soc.connect((hostname,port_number))
Standard EXAMPLE of socket connection
SERVER & CLIENT
run this in your IDLE
import time
import socket
import threading
HOST = 'localhost' # Standard loopback interface address (localhost)
PORT = 60000 # Port to listen on (non-privileged ports are > 1023)
def server(HOST,PORT):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
while True:
conn, addr = s.accept()
data = conn.recv(1024)
if data:
print(data)
data = None
time.sleep(1)
print('Listening...')
def client(HOST,PORT,message):
print("This is the server's hostname: " + HOST)
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
soc.connect((HOST,PORT))
soc.send(message)
soc.close()
th=threading.Thread(target = server,args = (HOST,PORT))
th.daemon = True
th.start()
After running this, in your IDLE execute this command and see response
>>> client(HOST,PORT,'Hello server, client sending greetings')
This is the server's hostname: localhost
Hello server, client sending greetings
>>>
If you try to do server with port 60000 but send message on different port, you will receive the same error as in your OP. That shows, that on that port is no server listening to connections

Connecting to a simple sockets python server remotely

I am trying to setup a very simply sockets app. My server code is:
import socket
s = socket.socket()
host = socket.gethostname()
port = 1234
s.bind((host,port))
s.listen(5) #Here we wait for a client connection
while True:
c, addr = s.accept()
print "Got a connection from: ", addr
c.send("Thanks for connecting")
c.close()
I placed this file on my remote Linode server and run it using python server.py. I have checked that the port is open using nap:
PORT STATE SERVICE
22/tcp open ssh
80/tcp open http
1234/tcp open hotline
I now run the client.py on my local machine:
import socket # Import socket module
s = socket.socket() # Create a socket object
port = 1234 # Reserve a port for your service.
s.connect(("139.xxx.xx.xx", port))
print s.recv(1024)
s.close # Close the socket when done
However I am not getting any kind of activity or report of connection. Could someone give me some pointers to what I might have to do? Do I need to include the hostname in the IP address I specify in the client.py? Any help would be really appreciated!
I've just summarize our comments, so your problem is this:
When you trying to using the client program connect to the server via the Internet, not LAN.
You should configure the
port mapping on your router.
And however, you just need configure the
port mapping for your server machine.
After you did that, then you can use the client program connect to your server prigram.

Categories

Resources