Python Client Server with Docker - Connection refused - python

I'm trying to develop a simple client/server application in python.
The client is running in a Docker container whereas the server is running directly on the host machine.
Here is the code of the client:
import socket
def main():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 8888))
print (Connected to server)
if __name__ == '__main__':
main()
and here is the code of the server:
import socket
HOST = '127.0.0.1'
PORT = 8888
print ("Serving on ", PORT)
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)
I have the following error:
File "./main.py", line 5, in main
s.connect(('127.0.0.1', 8888))
ConnectionRefusedError: [Errno 111] Connection refused
If I run this client outside a container (directly on host machine), i can connect. But I have this error when I run it in a container.
PS: It's not pure Docker container but an IoT Edge module
Do you know what is the problem ?
Thanks

first s.connect(('127.0.0.1', 8888)) in the container means to connect to the container itself not the host, to make that works you should run your Container with --network=host
second Option is to supply your host IP address to the client:
s.connect(('HOST_ROUTABLE_IP_ADDRESS', 8888))

Related

Python socket ipv6 over network not working

I am trying to connect a server to a client in python with sockets.
The problem is that with ipv6 binding, it works on my local network. What I want is to connect it to another network. These programs are written in Python 3
Here is the code of server.py:
import socket
HOST = someip
PORT = someport
server = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen()
Source code of client.py:
import socket
HOST = someip
PORT = someport
client = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
client.connect((HOST, PORT))
I think it is a port forwarding problem.
I know the code does nothing right now, but I want to first establish the connection.
When the server receives a request, we need to put it in a loop to accept it.
Like this
import socket
HOST = someip
PORT = someport
server = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen()
while True:
try:
conn, addr = server.accept()
print(f"New request from {addr}")
except KeyboardInterrupt:
server.close()

Heroku: ErrorTimeout connecting to a socket

I'm having problems with a simple socket connection to an Heroku app.
This is my server:
import socket
import os
import time
import sys
server = socket.socket()
port = int(os.environ.get("PORT", 12344))
host = "0.0.0.0"
server.bind((host, port))
print(f"###### SERVER RUNNING ON PORT {port} ({host}) ######")
server.listen()
while True:
s, addr = server.accept()
print("Recived request from:", addr)
print(addr, " sent: ", repr(s.recv(1024)))
print("Answering to:", addr)
s.send("Hello, world! (from server)".encode())
print("Answered to:", addr)
s.close()
It builds and run perfectly on Heroku(it receives also socket connection, not from me...by at this time, I don't care much about it)
This is my client:
import socket
import sys
HOST = 'app_name.herokuapp.com/' # The server's hostname or IP address
PORT = int(sys.argv[1]) # The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
print("connecting to " + HOST +":"+str(PORT))
s.connect((HOST, PORT))
print(s)
s.sendall("HI!!!".encode())
data = s.recv(1024)
print('Received', repr(data))
Running the client, after a while it returns:
File "./client.py", line 14, in <module>
s.connect((HOST, PORT))
TimeoutError: [Errno 110] Connection timed out
I don't know how to connect to it...am I missing something?
The problem is linked to the fact that Heroku app allow only http(s) connections. I honesty didn't found any Heroku docs that conferm it but the Daniel Chin' answer to this question make sense to me.
However, move the server.py to AWS worked for me (EC2 with t2.micro is free for the first year!!)

ConnectionRefusedError when trying to host python socket server on raspberry pi

I'm trying to make a basic python networking program. All I'm trying to do is send strings of text back and forth between the server and the client. I'm trying to host the server on my Raspberry Pi, and connect with a client on Windows 10. The program works great locally on my computer, but when I try to connect to my server, it gives me ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it. My server code is as follows:
import socket # Import socket module
import netifaces as ni
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port))
#host_ip = ni.ifaddresses('wlan0')[ni.AF_INET][0]['addr']
host_ip = "bruh?"
print("Server started! \nHostname: " + host + " \nIP: " + host_ip + " \nPort: " + str(port))
s.listen() # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print('Got connection from', addr)
output = "Welcome to the server!".encode()
c.send(output)
c.close()
Client code:
import socket
s = socket.socket()
host = 192.168.1.21
port = 12345
s.connect((host, int(port)))
noResponse = False
serverResponse = s.recv(1024).decode()
print(serverResponse)
s.close()
Does anyone know what my problem is? Thanks.
There may be a few reasons you are getting a ConnectionRefusedError, please try the following:
Check that no firewall is blocking your connection.
Double-check the server IP, if it is wrong you may get this error.
Try to use Hercules to check the connection.
Also, I would change the code as follow:
Server:
import socket
HOST = '' # localhost
PORT = # IMPORTANT !! Do not use reserved ports
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind((HOST, PORT))
sock.listen()
conn, addr = sock.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
print('Data: ',data)
conn.sendall('RT')
Client:
import socket
HOST = '' # server IP address
PORT = # server port
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.connect((HOST, PORT))
sock.sendall('Hello, I am the Client')
data = sock.recv(1024)
print('Received', data)
By doing this you are using a TCP connection and you can test your code with different TCP server and client emulators.

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

Python- run socket script on the remote linux host

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!

Categories

Resources