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
Related
I have the following setup:
The unit constantly tries to connect to the Remote Server on a specific known port.
On the Remote Server, there is nothing but open TCP ports.
I want to forward the Remote Server's port to My Pc and open a TCP Server to read the data.
Eventually, I want to use Python to implement this,
but in the meantime, I'm trying to use ssh to do this: ssh -N -R 10000:localhost:10000 username#hostname,
and on my side (My Pc), I tried to open a socket (with python) to listen to port 10000, and tried to open Hercules to simulate a TCP server, however, I didn't receive any data.
obviously, something is missing, what is it?
p.s. opening a TCP server on the Remote Server will get the data,
but I need to control the connections from My Pc.
If needed I will provide the python code that is using sshtunnel.SSHTunnelForwarder (which is not working 😔)
this should be the Python code to implement the ssh tunnel:
from sshtunnel import SSHTunnelForwarder
import socket
SSH_SERVER = 'hostname'
SSH_USERNAME = 'ubuntu'
SSH_PASSWORD = 'password'
PORT = 10_000
with SSHTunnelForwarder(ssh_address_or_host=SSH_SERVER,
ssh_username=SSH_USERNAME,
ssh_password=SSH_PASSWORD,
remote_bind_address=('0.0.0.0', PORT),
local_bind_address=('127.0.0.1', PORT),
) as server:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(('127.0.0.1', PORT))
s.listen(1)
conn, addr = s.accept()
with conn:
print(f"Connected by {addr}")
data = conn.recv(128)
print(data)
for MVP:
here is a unit simulator:
import socket
SSH_SERVER = 'hostname'
PORT = 10_000
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((SSH_SERVER, PORT))
s.sendall(b"Hello, world")
I want to see the b"Hello, world" in the print(data)
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.
For the following code, each time I connect to the server, I see two connections per each browser request. What is wrong and how to fix this?
$ sudo python3 host.py
Connected by ('127.0.0.1', 60810)
Connected by ('127.0.0.1', 60812)
Browser:
http://localhost:65432/
host.py :
#!/usr/bin/env python3
import socket
HOST = '127.0.0.1' # Standard loopback interface address (localhost)
PORT = 65432 # 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()
while True:
conn, addr = s.accept()
with conn:
print('Connected by', addr)
data = conn.recv(1024)
conn.sendall(data)
Also, each time I press ^C, and run the script again, I get
Traceback (most recent call last):
File "host.py", line 9, in <module>
s.bind((HOST, PORT))
OSError: [Errno 98] Address already in use
for one minute and cannot connect during this time. It looks like a timeout.
Your browser tries to connect several times, that's the two connections you see.
The system will keep the bound port open for some time after the owning process goes down. If you try to bind to the same port again within this time you'll receive Address already in use. You can set the SO_REUSEADDR flag to be able to instantaneously reuse the port:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Note: there is no need to use sudo as long as your port number is greater than 1024.
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
I have uploaded the server script to the public directory on the server machine. Then I try to connect to the server by a client, but I am not being connected. Here is my code snippets:
# Echo client program
import socket
HOST = 'www.dotpy.ir/server.py' # The remote host
PORT = 50007 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)
server:
# Echo server program
import socket
HOST = '' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.send(data)
conn.close()
These scripts seem to work well.
However, the script at the server must be run on the server for this to work. It's not enough for it to be uploaded to the public file area. What access do you have to the servers? Can you have scripts running on them?
If you succeed in running the script, then you will have to change the client script from:
HOST = 'www.dotpy.ir/server.py' # The remote host
to
HOST = 'www.dotpy.ir' # The remote host
The reason is that you will connect to the host itself. There the script will be running, listening to any inbound connections on the port specified. You can't conect to a specific script.
Good luck!