python connect to server on same network - python

I have got a server.py and a client.py.
If i run them on the same computer using the same port and host as 127.0.0.1 it works fine.
I got another laptop connected to the same network. I got my local ip address 129.94.209.9 and used that for the server. On the other laptop I tried connecting to the server but I couldn't.
Is this an issue with my code, with the network or I'm just using the wrong ip address?
Server.py
HOST = '129.94.209.9'
PORT = 9999
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen(10)
sockfd, addr = server_socket.accept()
send and receive messages etc....
Client.py
HOST = '129.94.209.9'
PORT = 9999
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((HOST, PORT))
except:
print("Cannot connect to the server")
send and receive messages etc...
Client prints "Cannot connect to the server"
Thanks!!
UPDATES: thanks for the comments
1) I did do sockfd, addr = server_socket.accept() sorry I forgot to add it, it was a few lines further down in the code.
2) The error is: [Errno 11] Resource temporarily unavailable
3) Ping does work
EDIT: It is working now when I plug both computers in by ethernet cable to the same network. Not sure why my the won't work when they are right next to each other connected to wifi.
Thanks for all the suggestions! I'll investigate the network issue myself

Using the following code (my IP address rather than yours, of course) I see the expected behaviour.
so8srv.py:
import socket
HOST = '192.168.33.64'
PORT = 9999
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen(10)
print("Listening")
s = server_socket.accept()
print("Connected")
so8cli.py:
import socket
HOST = '192.168.33.64'
PORT = 9999
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((HOST, PORT))
except Exception as e:
print("Cannot connect to the server:", e)
print("Connected")
When I run it, the server prints "Listening". When I then run the client, both it and the server print "Connected".
You will notice that, unlike your code, my client doesn't just print hte same diagnostic for any exception that's raised, but instead reports the exception. As a matter of sound practice you should avoid bare except clauses, since your program will then take the same action whether the exception is caused by a programming error or a user action such as KeyboardInterrupt.

Also try using this construction to obtain the IP address:
HOST=socket.gethostbyname(socket.gethostname())

Related

Python Socket connect from another network

I had done port forwarding which ask me for Internal IP, Internal Port, External Port and Protocol.
For internal ip i write device's ip which server.py runs in, for internal and external ports 23456, and for protocol i choose TCP
Server.py
import socket
port = 23456
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', port))
s.listen(1)
except socket.error as msg:
print(msg)
while True:
c, addr = s.accept()
txt = 'Connected'
print(addr)
c.send(txt.encode('utf-8'))
c.close
Client.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 23456
try:
s.connect(('public ip address',port))
re = s.recv(1024)
print(re.decode('utf-8'))
s.close()
except socket.error as msg:
print(msg)
When i start Server.py and Client.py later, nothing happens. Looks like it doesn't connect to the server.I run both files on same device (i think it isn't problem) (and i can't try it on devices which at different networks for now)
Try binding to address 0.0.0.0
How to:
s.bind(('', port))
into
s.bind(('0.0.0.0', port))
And a reminder to change c.close into c.close() on Server.py

nonstop server client connection[Python]

I want to create a server-client connection that the client can always be connected to the server. How can I do it? Please help me. when I was trying, this error occurred.
"ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host"
- code -
server:
import socket
try:
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(1)
conn, addr=s.accept()
while True:
conn.send(("Test message").encode())
print((conn.recv(1024)).decode())
except Exception as error:
print(str(error))
client:
import socket
try:
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((server_host,port))
while True:
print((s.recv(1024)).decode())
s.send(("Test message").encode())
except Exception as error:
print(str(error))
Some reasons cause this error message:
Server reused the connection because it has been idle for too long.
May be Client IP address or Port number not same as Server.
The network between server and client may be temporarily going down.
Server not started at first.
Your code seems to be OK. Did you run the Server at first time then client? Please make sure it. The below code fully tested on my computer.
Server:
import socket
HOST = '127.0.0.1' # (localhost)
PORT = 65432 # Port to listen on
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
while True:
data = conn.recv(1024).decode()
if not data:
break
conn.send(data.encode())
Client
import socket
HOST = '127.0.0.1' # Server's IP address
PORT = 65432 # Server's port
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
while True:
s.send(("Hi server, send me back this message please").encode())
data = s.recv(1024).decode()
print('(From Server) :', repr(data))
Note: Run the Server first then Client.
Output:

Python Basic Client Server Socket Programs

I tried the basic programs for client and server from realpython (https://realpython.com/python-sockets/#echo-client-and-server)
While these work fine when running on the same computer, there is following problem when trying on different machines:
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
Client code:
HOST = '10.0.0.55' # The server's hostname or IP address
PORT = 65432 # The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b'Hello, world')
data = s.recv(1024)
print('Received', repr(data))
Server Code:
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()
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
I can make pings from one computer to the other.
Firewall is turned down
Wireshark shows that the SYN message arrives on the second computer which is answered by a RST message (Wireshark PC server)
If you want the server to be open to other computers, you can't listen on 127.0.0.1 which is basically an inner local loop only located on the computer running the program (that's why it's called loopback in comments). You should have the server listen on its own real address (for example: 10.0.0.55 explicitly).
This however can be annoying if your host can change addresses, an easy workaround is to just use the local IP address like this (on the server):
HOST = socket.gethostbyname(socket.gethostname())
Or if you specifically want to use the address from one network interface:
HOST = '10.0.0.55'
Or, if you want to listen on all network interfaces:
HOST = '0.0.0.0'

Getting error non-blocking (10035) error when trying to connect to server

I am trying to simply send a list from one computer to another.
I have my server set up on one computer, where the IP address is 192.168.0.101
The code for the server:
import socket
import pickle
import time
import errno
HEADERSIZE = 20
HOST = socket.gethostbyname(socket.gethostname())
PORT = 65432
print(HOST)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(10)
while True:
conn, adrs = s.accept()
print(f"Connection with {adrs} has been established")
conn.setblocking(1)
try:
data = conn.recv(HEADERSIZE)
if not data:
print("connection closed")
conn.close()
break
else:
print("Received %d bytes: '%s'" % (len(data), pickle.loads(data)))
except socket.error as e:
if e.args[0] == errno.EWOULDBLOCK:
print('EWOULDBLOCK')
time.sleep(1) # short delay, no tight loops
else:
print(e)
break
The client is on another computer. The code:
import socket
import pickle
HOST = '192.168.0.101'
PORT = 65432
def send_data(list):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(10)
print(".")
print(s.connect_ex((HOST, PORT)))
print(".")
data = pickle.dumps(list)
print(len(data))
s.send(data)
s.close()
send_data([1,1,1])
The outputted error number of connect_ex is 10035. I read a lot about the error, but all I found was about the server side. To me, it looks like the problem is with the client and that it is unable to make a connection to 192.168.0.101. But then, I don't understand why the error I get is about non-blocking.
What is it that I am doing wrong that I am unable to send data?
First of all, how user207421 suggested, change the timeout to a longer duration.
Also, as stated here Socket Programming in Python raising error socket.error:< [Errno 10060] A connection attempt failed I was trying to run my server and connect to a private IP address.
The fix is: on the server side, in the s.bind, to leave the host part empty
HOST = ''
PORT = 65432
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
And on the client side, use the public IP of the PC where the server is running (I got it from ip4.me)
HOST = 'THE PUBLIC IP' #not going to write it
PORT = 65432
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, PORT))

How to exchange data on different networks using sockets?

I know this was already asked but the previous questions didn't help. I'm trying to send some data using sockets. Specifically I'm using my laptop as server and a Linux emulator (Termux) on my smartphone as a client. Here below you can see the two Python codes. For the server:
import socket
HOST = ''
PORT = 5555
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
s.close()
And for the client:
import socket
HOST = ''
PORT = 5555
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall(b'Hello, world')
data = s.recv(1024)
print('Received', repr(data))
s.close()
When I'm connected to the same WiFi and in HOST (in both codes) I put the IP I see from ipconfig (192.168.---.---) everything works. It also works if in the HOST of the server I put 0.0.0.0.
However, when I put the IP of the machine (that I can see on https://whatismyipaddress.com/) and instead of using the WiFi I use the phone connection I get: ConnectionRefusedError: [Errno 111] Connection Refused.
Can someone explain me how can I connect client and server when the networks are different? I have been stuck with this for a while.
I also tried to open a port on the Firewall following this procedure and put it in the code instead of 5555 but still it didn't work.
Thank you in advance for the help.

Categories