Connecting a TCP client to my server from external IP - python

I have made a simple TCP server and client in Python. Everything works fine when I use the local IP of the server, but not with the public IP. My server has a static IP and is bound to this IP and a port, and the client is trying to connect to the public IP with the same port. I've set up port forwarding on my router to supposedly redirect traffic to that port to the server's local IP. The router is a Netgear X4S R7800.
Neither the server nor the client crash at any point. The client just times out eventually and throws an exception, and the server doesn't seem to receive any connection at all.
Server.py
from socket import *
SERVER_NAME = '192.168.1.140' #My server's (static) local IP
SERVER_PORT = 12100
def initializeServer():
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind((SERVER_NAME, SERVER_PORT))
serverSocket.listen(5)
print("Server initialized to port " + str(SERVER_PORT) +"...")
return serverSocket
def serverLoop(serverSocket):
while True:
connectionSocket, addr = serverSocket.accept() #Gets stuck here
print("Connected to", addr)
listenToClient(connectionSocket)
print("Terminating client connection ...")
connectionSocket.close()
if __name__ == '__main__':
serverSocket = initializeServer()
try:
serverLoop(serverSocket)
except KeyboardInterrupt:
shutdownServer(serverSocket)
print("\nServer shut down")
Client.py
import socket
SERVER_NAME = '193.91.XXX.XXX' #Public IP
SERVER_PORT = 12100
def connectToServer(serverName, serverPort):
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientSocket.connect((serverName, serverPort)) #Gets stuck here and eventually times out
return clientSocket
def main():
try:
serverSocket = connectToServer(SERVER_NAME, SERVER_PORT)
except Exception as e:
print("Cannot connect to the server\n", e)
else:
print("Connected to server")
try:
askForUserAction(serverSocket)
except KeyboardInterrupt:
serverSocket.close()
if __name__ == '__main__':
main()

Alright, I solved it. My modem provided by my ISP is apparently also a router. I have another router and I was connected to and forwarding ports from this one. Just had to change the setting of my ISP's router and it worked fine.

Related

How to connect with Python Sockets to another computer on the same network

So I was trying to figure out a way to use sockets to make a terminal-based chat application, and I managed to do it quite well. Because I could only test it on one computer, I didn't realize that it might not work on different computers. My code is as simple as this:
# Server
import socket
HOST = "0.0.0.0"
PORT = 5555
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 to", addr)
data = conn.recv(1024)
print("Received:", data.decode())
conn.sendall(data)
# Client
import socket
HOST = "192.168.0.14"
PORT = 5555
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b"Hello this is a connection")
data = s.recv(1024)
print("Received:", data.decode())
I've tried changing the ip to 0.0.0.0, use gethostname a lot of other things, but it just doesn't work. The server is up and running, but the client can't connect. Can someone help me?
I believe that 0.0.0.0 means connect from anywhere which means that you have to allow port 5555 through your firewall.
Instead of 0.0.0.0 use localhost as the address in both the client and the server.
I just tested your code using localhost for the server and the client and your program worked.
server:
Connected to ('127.0.0.1', 53850)
Received: Hello this is a connection
client:
Received: Hello this is a connection
As you can see, all that I changed was the address on both the server and the client. If this doesn't work then there is something outside of your program that is preventing you from success. It could be a permissions issue or another program is listening on port 5555.
server.py
# Server
import socket
HOST = "0.0.0.0"
HOST = "localhost"
PORT = 5555
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 to", addr)
data = conn.recv(1024)
print("Received:", data.decode())
conn.sendall(data)
if __name__ == '__main__':
pass
client.py
# Client
import socket
HOST = "localhost"
PORT = 5555
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b"Hello this is a connection")
data = s.recv(1024)
print("Received:", data.decode())
if __name__ == '__main__':
pass

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:

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))

Python Socket connect two devices on same network

I am attempting to connect a simple server and client from two computers on the same network. Both the client and server cannot 'find' each other, as they do not move past .connect() and .accept() respectively. What am I doing wrong?
(Windows 10)
Server:
import socket
HOST = socket.gethostname() #Returns: "WASS104983"
#I have also tried socket.gethostbyname(socket.gethostname)), returning: "25.38.252.147"
PORT = 50007
sock = socket.socket()
sock.bind((HOST, PORT))
sock.listen(5)
print("Awaiting connection... ")
(clnt, addr) = sock.accept()
print("Client connected")
…
and Client:
import socket
HOST = "WASS104983" #Or "25.38.252.147", depending on the servers setup
PORT = 50007
sock = socket.socket()
print("Attempting connection... ")
sock.connect((HOST, PORT))
print("Connected")
…
I have gotten this to work before so I am not sure why it's not now.
I know there are a few questions of this calibre, but none seem to cover my problem.
Also, a wifi extender should not interfere with local transmissions should it?
I have always seen servers setup as such:
import socket
import threading
bind_ip = '0.0.0.0'
bind_port = 9999
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((bind_ip, bind_port))
server.listen(5)
print("[*] Listening on {}:{}".format(bind_ip, bind_port))
def handle_client(client_socket):
request = client_socket.recv(1024)
print('received: {}'.format(request))
client_socket.send(b'ACK!')
client_socket.close()
while True:
client, addr = server.accept()
print("[*] Accepted connection from: {}:{}".format(addr[0], addr[1]))
client_handler = threading.Thread(target=handle_client, args=(client,))
client_handler.start()*
Where I think an important distinction from your post may be that the server accepting connections is within an infinite loop. Have you tried this?

I'm having a problem with my Python socket program [WinError 10057]

I was programming a simple client-server socket program that worked on two different computers.
The server is a desktop with a static ip address, and the client is a laptop connected to a Wi-Fi. Both are using Windows 10 as operating system.
I also opened the firewall port.
Here is my code.
This code works well within one computer, but WinError 10057 occurs when another computer(my laptop) tries to connect to the server.
server.py
from socket import *
import sys
HOST = '0.0.0.0'
PORT = 16161
BUFSIZE = 1024
ADDR = (HOST, PORT)
CLIENT_NUM = 5
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(ADDR)
print('bind')
serverSocket.listen(CLIENT_NUM)
print('listen')
while True:
try:
connectionSocket, addr_info = serverSocket.accept()
print('accept')
print('--client information--')
print(connectionSocket)
data = connectionSocket.recv(BUFSIZE)
print('Received data:', data.decode())
connectionSocket.send('OK'.encode())
connectionSocket.close()
except KeyboardInterrupt:
sys.exit(0)
client.py
from socket import *
import sys
HOST = '*.*.*.*' # server's ip address
PORT = 16161
BUFSIZE = 1024
ADDR = (HOST, PORT)
clientSocket = socket(AF_INET, SOCK_STREAM)
try:
clientSocket.connect_ex(ADDR)
clientSocket.send('Hello!'.encode()) # WinError 10057 occurs
except Exception as e:
print(e)
print('%s:%s' % ADDR)
sys.exit(1)
print('connect is success')
receive = clientSocket.recv(BUFSIZE)
print(receive.decode())
clientSocket.close()
I've fixed it. I asked my organization to open the firewall ports, and the connection was successful when the firewall ports were opened.

Categories