Why is "connection refused" error occuring - python-3.x

This is client.py class and This class is on mobile.
import socket
c = socket.socket()
c.connect(('127.0.0.1', 9998))
name = input("Enter your name : ")
c.send(bytes(name, 'utf-8'))
data = c.recv(1024).decode()
print(data)
This is server.py class and This class is on mac book pro.
import socket
s = socket.socket()
s.bind(('localhost', 9998))
s.listen(2)
print('server is waiting for connections..')
while True:
c, addr = s.accept()
name = c.recv(1024).decode()
print('connected with', addr, name)
st = "Hello, " + name
c.send(st)
c.close()
Why am I getting "connection refused" error?

Your client and server are running on different devices. Your client is trying to connect to the local loopback IP 127.0.0.1, which will work only if the server is running on the same device as the client. That is why you are getting "connection refused" - there is no server listening locally at 127.0.0.1:9998.
If the client and server are connected to the same network (WiFi, etc), the client needs to connect to the server's actual LAN IP on that network.
If the client and server are connected to different networks (ie, they reach each other over the Internet), the client needs to connect to the public IP of the network that the server is connected to, and that network router will need to have port forwarding configured to route incoming connections to the server device.
Also, note that making the server listen on localhost does not guarantee it will be able to accept clients from other devices, depending on how localhost is implemented. It might resolve to 127.0.0.1 only. The server should instead listen on the wildcard IP 0.0.0.0 so it listens on all available network interfaces that are installed on that device. Or, it can alternatively listen on just the specific LAN IP that will actually be receiving the client connections.

To echo what Remy just correctly said, "connection refused" is really a bit misleading. It basically means that there was no one listening at the address-and-port that the host tried to reach. It does not mean that "there was someone there, but he [actively ...] 'refused to' talk with you." "Connection failed" might have been a better term, but, here we are.

Related

Why cant my friend not connect to my socket

so im trying to establish connection between my friends pc and my pc but it keeps saying the host failed to respond
this is the client
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("192.168.0.177", 1234))
msg = s.recv(1024)
print(msg.decode("utf-8"))
and this is the server
import socket
s = socket.socket(socket.AF_INET
, socket.SOCK_STREAM)
s.bind(('192.168.0.177', 1234))
s.listen(5)
while True:
clientsocket, address = s.accept()
print(f'conection from {address} has bene establish')
clientsocket.send(bytes("welcome to the server", "utf-8"))
Update/Edit
so i tried my public IP address and it says
WinError 10049] The requested address is not valid in its context
the error is serverside
In the comments, you say that your friend is on a different LAN as you. The reason that he can not reach your server is because he is trying to reach your server on your LAN by connecting to an address (192.168.0.177) in the 192.168.x.x. space from his LAN.
See https://en.wikipedia.org/wiki/Private_network, where it explains that addresses in the 192.168.0.0 – 192.168.255.255 range are reserved for private networks. As such, IP packets originating from or addressed to a private IP address cannot be routed through the public Internet.
To solve this problem, you should setup a port-forwarding rule your router, to forward incoming connections to port 1234 on the public side of your router to 192.168.0.177:1234 on the private side of your router. Then, your friend should connect to xxx.xxx.xxx.xxx:1234, where xxx.xxx.xxx.xxx is the public IP address of your router. You can find the public ip address of your router by pointing your web browser to www.whatismyip.com from a computer on your LAN. If the port-forwarding is working correctly, your router should forward the incoming connection from your friend to your server at 192.168.0.177:1234 running on your private LAN.
The IP range 192.168.0.0 to 192.168.255.255 (192.168.0.0/16) is considered to be the private range. Even if you design your routers to force the packets from these sources to the outside internet world, other routers will be discarding the packets.
You need to have both the machines on the same LAN or you need to set up a network on your own and configure routers (routing tables) in between or a public IP for accepting connections.

The UDP socket cannot receive replies when connect function is used on Linux

I write a udp server and client using Python. The code is simple. When the udp client sends data to the server, the server replies a message to the client.
The server code is as follows, the filename is "serverudp.py".
#!/usr/bin/env python
from socket import *
HOST = ''
PORT = 19998
s = socket(AF_INET,SOCK_DGRAM)
s.bind((HOST,PORT))
print '...waiting for message..'
while True:
data,address = s.recvfrom(1024)
print data,address
s.sendto('this is the UDP server',address)
s.close()
The client code is as follows, the filename is "clientudp.py"
#!/usr/bin/env python
from socket import *
HOST='10.0.0.12'
PORT=19998
addr=(HOST,PORT)
s = socket(AF_INET,SOCK_DGRAM)
s.connect(addr)
while True:
message = raw_input('send message:>>')
s.sendto(message, addr)
data = s.recv(1024)
print data
s.close()
The client can not receive the any reply. However, if I comment the following
connect line in the client code, it works correctly.
#s.connect(addr)
As the same client code works well on another Linux machine with the connect line, so I want to know what's the problem with my Linux machine? Is there any Linux kernel restriction or TCP/UDP socket restriction with it?
I hope your answers, thank you!
You have an assumption in your code that may be incorrect. By passing 10.0.0.12 to connect, you are configuring your client to only accept incoming datagrams with a source IP address of 10.0.0.12. But nothing in your server either ensures that the source IP address is 10.0.0.12 or that the source IP address will match the destination address of the corresponding query.
Consider:
Client connects to 10.0.0.12:19998
Client sends datagram to 10.0.0.12:19998 with one of its IP addresses as the source address.
Server receives query sent to 10.0.0.12:19998.
Server forms response to the source IP address of that datagram and goes to send it.
Server chooses some source IP address other than 10.0.0.12 because it seems "closer" to the destination. The server's IP stack has no idea this datagram is in any sense a reply to the received datagram and so has no reason to set the source IP address to 10.0.0.12.
Client rejects the reply because it is connected to 10.0.0.12 and the reply is from some other IP address.
The short version of the solution is not to use connect for UDP unless the server is guaranteed to always send a reply datagram with a source IP address that matches the IP address the client is going to connect to. Nothing in your setup assures this.
The usual solution is to never bind a UDP socket to a wildcard IP address. Instead, bind the socket to the specific IP address the server is going to use to communicate with its clients.

Why is my Socket Client not allowing the outgoing connection in python 3?

I have created a very simple UDP Socket client and server in python3.
I'm trying to send the simple message 'hello' to the server and I am getting the error:
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
I'm not sure that it's actually the target machine's fault as the target machine is an AWS EC2 Ubuntu instance with 'All Traffic Allowed' configured with the security group.
I'm convinced it has to be some sort of outbound policy on my desktop computer...
Any help is appreciated.
Here is my code:
client.py
import socket
client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_sock.connect(('servers public ipv4 ip', 8089))
client_sock.send('hello'.encode())
server.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('localhost', 8089))
s.listen(5) #5 connections
while True:
conn, addr = s.accept()
buffer = conn.recv(64)
if len(buffer) > 0:
print(buffer.decode())
break
First, despite your repeated claims (in body and tags) that you are using UDP you are actually using TCP as can be seen from your use of SOCK_STREAM and accept.
s.bind(('localhost', 8089))
You explicitly bind the server to localhost. But localhost is only the loopback interface of the computer (127.0.0.1) which is not reachable from outside. If you want to accept connections from other systems you need to either bind to the IP address of the specific network interface or broadly to 0.0.0.0 - or simply use s.bind('',8089).

Basic UDP networking doesn't receive

I'm trying to learn UDP networking so I tried the simplest code to begin with. It's a python code client-server that works perfectly when I send data to localhost or to the LAN IP from the same computer, but it doesn't work when I try to send from my computer using the public IP, and also doesn't work from another computer using private network IP or public IP.
I did the port forwarding, created the input rules for windows firewall, turned off the router internal firewall, and it still doesn't work.
When I scan my port from canyouseeme.org or using netcat it says connection refused and port closed.
Maybe somebody can guess what is happening here or what may I do to succeed?
I write the code below in case it's needed.
Server:
import socket
UDP_IP = "0.0.0.0"
UDP_PORT = XXXX
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
while True:
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
message = data.decode()
print("received message:", message)
Client:
import socket
UDP_IP = "192.168.1.133"
UDP_PORT = XXXX
MESSAGE = "Hello, World!"
print("UDP target IP:", UDP_IP)
print("UDP target port:", UDP_PORT)
print("message:", MESSAGE)
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.sendto(MESSAGE.encode(), (UDP_IP, UDP_PORT))
Thanks in advance.
After some investigation I have found a partial solution. I'm posting an answer because it may help some people with similar problems, but it's not the best solution yet, so the issue is still there.
I found that there's no problem in communicating within a LAN if I completely disable the firewall in both computers. I don't know why the input rules or exceptions don't work.
For networking beyond the LAN I have tried successfully to use a virtual LAN (i.e. hamachi) and there's no necessity of port forwarding nor disabling the firewall. The bad thing about hamachi is that I don't control the protocol it uses, and I don't control the way of ensuring reliability.
For the applications I'm dealing with right now I probably have enough with this solution, but it would be interesting to know more.

Create a virtual serial port connection over TCP

I am developing an application that should be able to write to a virtual serial port and receive data through the same port from remote clients over network.
The application runs on a linux server. I am new in using serial ports and I have some questions on this topic.
Clients
The client can establish a TCP connection to a server. When we setup a client, we have to provide the IP address of the server, a tcp port (usually 8080) and a virtual com port.
The client then will automatically try to connect to the server.
Server
The server has a virtual com port, the same we set in the client config (e.g. COM1). When an application on the server writes data to this port, the data should be send to all clients connected via tcp. The response from the clients is send over TCP back to the server which can read it over the virtual serial port.
Question
On windows I used a virtual serial port connector http://www.eterlogic.com/Products.VSPE.html which did most of the work. However I want to solve this problem on linux machines.
My question is, how can I create a TCP server that has a virtual serial port attached and can send/receive data through this port over TCP to listening clients?
Try socat. Possible scenario:
socat pty,link=/dev/virtualcom0,raw tcp:192.168.254.254:8080&
socat creates TCP connection to 192.168.254.254:8080, so that everything, that will be written to /dev/virtualcom0 will be forwarded to 192.168.254.254:8080 and vice versa.
Another approach would be to use RFC2217 via ser2net on Linux sever side and RFC2217 driver on Windows side (for example http://www.hw-group.com/products/hw_vsp/index_en.html single port version). You can also try to get http://pyserial.sourceforge.net/ to work with ser2net.
you have socat and ser2net and other programs but my experience is very bad... not working properly. I've done this small python program, can be useful. Update port, baudrate... then use any tcp client. Remove first line if don't want to use is as auto executable script
#!/usr/bin/python
import socket
import sys
import serial
#open serial port
ser = serial.Serial('/dev/ttyAMA0', 115200, timeout=0)
#create socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
#bond to the port. Don't use localhost to accept external connections
server_address = ('', 2105)
print('starting up on {} port {}'.format(*server_address))
sock.bind(server_address)
#listen
sock.listen(1)
#loop
while True:
#waits for a new connection
print('waiting for a connection')
connection, client_address = sock.accept()
try:
print('connection from', client_address)
#continously send from serial port to tcp and viceversa
connection.settimeout(0.1)
while True:
try:
data = connection.recv(16)
if data == '': break
ser.write(data)
except KeyboardInterrupt:
connection.close()
sys.exit()
except Exception as e:
pass
received_data = ser.read(ser.inWaiting())
connection.sendall(received_data)
except Exception as e:
print e
finally:
#clean up connection
connection.close()
The software will help to establish server and client connection over TCP http://www.serial-com-port.com/
I use it for creating virtual serial communications over network, but I have the real RS232 port on the computer. So I just transfer the data over network. If you need to create a virtual COM on the server too, use the Virtual Serial Port Driver.

Resources