library socket: open port - python

I have try to create a little online game with python but I face a problem.
I have no problem as long as I work in local (same computer or private IP adresse) but the socket can't connect if i use an IP.
Server:
import socket
co_prin = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
co_prin.bind(('', 9000))
co_prin.listen(10)
co,info=co_prin.accept()
print('connexion recu')
co.close()
co_prin.close()
Client:
import socket
co_serv=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
adresse='81.56.76.61'
co_serv.connect((adresse, 9000))
print("Connecté.")
co_serv.close()
If I change adresse by 'localhost' there is no problem.
One tell me that the reason was python can't open the port. I would like to know if there is a solution to solve or bypass the problem easy to use for other user. (I can always create a local network with hamachi or open the port manually but it's wouldn't be easy to share my programm).
Edit, the error in the client code: Traceback (most recent call last):
File "", line 5, in
co_serv.connect((adresse, 9000))
socket.error: [Errno 10061] No connection could be made because the target machine actively refused it

You are not using your actual computer IP. You are using your public IP address.
Open cmd/command.com and type in the command: ipconfig.
You will there see a totally different IP (IPv4/IPv6 address):
Most likely you want this (do this for yourself!):
Then, if you want people outside your network want to access your computer you must port forward the port to your network IP address from your router.
If you are just experimenting with python, it's best to use 127.0.0.1 or localhost as IP-address.

Related

How to connect client in a internet to the server

I made a simple chat room. But I can't connect clients who joined through internet. I know I'm using local network to this program. But I researched how to connect my server to the internet. I used my Dynamic public IP and port forwarded using my router, but It didn't work. And I used ngrok, but it also didn't work. How can I solve this problem.
This is a part of my program.
IP_Address = 'IP'
Address = (IP_Address,PORT)
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(Address) # Bind IP address and Port to this socket.
When I used my public addressit shows this error.
Traceback (most recent call last):
File "Documents/Projects/Python/server.py", line 13, in <module>
server.bind(Address) # Bind IP address and Port to this socket.
OSError: [Errno 99] Cannot assign requested address
Use server.bind(('',port)) or server.bind(('0.0.0.0',port)). Both mean "bind to all interfaces".
If you want to bind to a specific interface, use your local IP, not the public one. Use ipconfig from the console to see your IP address.
On the router, forward the port to your local IP. Clients on the internet connect to your public IP and port.
I think the best way to solve this problem is using a Cloud Application Platform to run the server program.

Create TCP Server accessible on remote networks

A project I am working on has an Android app as a front-end and a Python program that would be used as the back-end.
I want to send data from the Android app (primarily images) to the Python program, do some processing and send the result back to the Android app.
I have found numerous tutorials that suggest using the socket module in python to create the server side, but all tutorials show the server on local network only (For testing purposes I created the client side also in Python, but it would be converted to Java later on)
The server code:
from requests import get
import socket
public_ip = get('https://api.ipify.org').text
print('My public IP address is: {}'.format(public_ip))
# getting the hostname by socket.gethostname() method
hostname = socket.gethostname()
# getting the IP address using socket.gethostbyname() method
local_ip = socket.gethostbyname(hostname)
# printing the hostname and ip_address
print(f"Hostname: {hostname}")
print(f"IP Address: {local_ip}")
#
HOST = local_ip
PORT = 80 # Port to listen on (non-privileged ports are > 1023)
with socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024).decode('utf-8')
if not data:
break
conn.sendall(data.encode('utf-8'))
The client code:
import socket
HOST = '…' # I modify it to the server's public IP address, as printed from the server code
PORT = 80 # The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
with socket.create_connection((HOST, PORT)) as s:
s.sendall(b'Hello, world')
data = s.recv(1024)
print('Received', repr(data))
Using the code above, if I try using any port other than 80 I get ConnectionRefusedError: [Errno 111] Connection refused. And for port 80, I get TimeoutError: [Errno 110] Connection timed out.
In both cases, I try to connect from a device on another network.
I tried to use the ping command in Windows CMD to check the connection to the server, and I get 'connection refused message'.
I understand that the Firewall is what probably blocks the connection, but I don't know how to bypass it. I added a new rule in the Inbound Rules section (as suggested on other websites) but for no avail… The results were the same.
How can I make the connection between remote devices on different networks?
Thanks in advance ☺
In order to connect to your server using a TCP socket connection, you need to make sure your server can listen on a port on a publically available IP address.
If the External IP address is assigned to your computer directly,
and if you run the server code on that computer, then the TCP port opened by the server code should be available on the internet.
However, IP addresses are often assigned to a modem/router in home networks,
instead of assigning them to any connected device directly.
To find out if your External IP address is assigned to the computer directly you can use tools that your OS support (eg. ipconfig on windows). If you can see the IP address returned by api.ipify.org, then it means your computer is connected directly. You can change your code to connect using publically exposed IP:
HOST = public_ip
If this is successful means your computer is assigned an external address directly. Which is highly unlikely.
There are several workarounds for this problem though:
1) Configure your router to forward port
Configure your router to forward all connections to it's external TCP port, to an internal host in your network which is assigned to your computer. Please find instructions how it is done for your router.
2) Setup a remote proxy
If you don't have permission to change your router settings you can set up a remote proxy listening on the TCP port. While there is a number of ways of doing this, very popular is to set up a remote SSH tunnel, for that you need to have a server with SSH access and an external IP. Run this command:
ssh -R 80:localhost:8080 root#your-ssh-server-host
You can also use a third-party service that exposes your private host on the internet like:
Ngrok (Commercial, with free plans)
Localtunnel (Open Source, can be self-hosted)

Python & Mcpi (minecraft) - connection refused error

I use mcpi: https://github.com/AdventuresInMinecraft/AdventuresInMinecraft-Linux
Starting the local server.
After, run program:
import mcpi.minecraft as minecraft
mc = minecraft.Minecraft.create()
mc.postToChat("Hello Minecraft World")
I am facing the below error:
Traceback (most recent call last):
File "/home/home/AdventuresInMinecraft/MyAdventures/HelloMinecraftWorld.py", line 2, in mc = minecraft.Minecraft.create()
File "/home/home/.local/lib/python3.6/site-packages/mcpi/minecraft.py", line 376, in create return Minecraft(Connection(address, port))
File "/home/home/.local/lib/python3.6/site-packages/mcpi/connection.py", line 17, in init self.socket.connect((address, port))
ConnectionRefusedError: [Errno 111] Connection refused
A ConnectionRefusedError means that the address + port combination was unable to be secured for this particular Minecraft server and thus raised an exception. This could be because some other application is already using the port of interest, the port is unavailable because of the OS, or a handful of other networking configuration mishaps.
But perhaps a better series of questions to ask yourself is:
What is the default address and port that minecraft.Minecraft.create() will attempt to launch / listen at?
Do I have access to that server (address + port)?
If I do have access, are there any security issues (AKA Firewall)?
This post has already addressed the root issue of your question, and I hope it gives you a good start at understanding the foundation of your problem.
Notice how their question mentions s.connect((host,port)) and your stack trace has self.socket.connect((address, port)) Looks like the same thing to me!
Some more reading:
- localhost
- check if port is in use
I encountered the same issue. I looked into the code of mcpi and found that the default port is 4711. However, a Minecraft Server's default port is 25565. All you need to do is add 2 parameters on the create() function. Code(Python):
mc = minecraft.Minecraft.create(address="127.0.0.1", port=25565)
btw change "address" in the code to the host of the server (only if you modified the "server.properties" file).
Also, ConnectionRefusedError doesn't mean that it's not secured, I believe it means that either the server is not online, it doesn't exist, or the server refused it for some reason.
EDIT:
Oops sorry I just found out that mcpi actually connects to the RaspberryJam plugin which is hosted on another IP and port. The plugin runs on port 4711. So mcpi has the right port.
So check if you have the RaspberryJam plugin installed. If not, download it from
https://www.spigotmc.org/resources/raspberryjuice.22724/
And put the .jar file inside the plugins folder in your server directory.

Python 2.7 [Errno 113] No route to host

I have 2 computers on the same LAN. The first PC has an ip address 192.168.178.30, the other PC has an ip address 192.168.178.26.
Ping, traceroute, telnet, ssh, everything works between the two PCs. Both PCs run the same OS - CentOS 7 and both PCs have the same python version 2.7.5 (checked with the python -V command).
I copied simple python code from a computer networking book.
client.py
from socket import *
serverName = '192.168.178.30'
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName,serverPort))
sentence = raw_input('Input lowercase sentence: ')
clientSocket.send(sentence)
modifiedSentence = clientSocket.recv(1024)
print 'From Server:', modifiedSentence
clientSocket.close()
server.py
from socket import *
serverPort = 12000
serverSocket = socket(AF_INET,SOCK_STREAM)
serverSocket.bind(('192.168.178.30',serverPort))
serverSocket.listen(5)
print 'The server is ready to receive'
while 1:
connectionSocket, addr = serverSocket.accept()
sentence = connectionSocket.recv(1024)
capitalizedSentence = sentence.upper()
connectionSocket.send(capitalizedSentence)
connectionSocket.close()
The code works when it is ran on the same PC (where the server is listening on localhost).
When I run the client code on one PC and the server code on the other PC I get this error on the client side.
Traceback (most recent call last):
File "client.py", line 5, in <module>
clientSocket.connect((serverName,serverPort))
File "/usr/lib64/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 113] No route to host
Can someone help?
Check the firewall (on the server).
I stopped the firewall like Messa suggested and now it works.
service firewalld stop
I still don't understand what the problem was. I even tried using different distributions. Do all distributions have strict firewalls or something. For example Ubuntu to Ubuntu, Ubuntu to CentOS, CentOS to Ubuntu I still had the same problem (error).
~]#supervisord
Error: No config file found at default paths (/usr/etc/supervisord.conf, /usr/supervisord.conf, supervisord.conf, etc/supervisord.conf, /etc/supervisord.conf); use the -c option to specify a config file at a different path
For help, use /usr/bin/supervisord -h
You should use
ln -s /etc/supervisor/supervisord.conf /usr/etc/supervisord.conf
None of this stuff worked for me. I just connected both the devices to the same WiFi network and my program worked!
You can also get this same error ([Errno 113] No route to host) if you are trying to connect 2 devices on the same network. the error can be fixed by double checking to make sure both devices are connected to the mqtt_client or whatever you are using. as soon as I connected the device I was trying to talk to everything worked as to be expected.I would also check to make sure the right IP_Address is being passed
We had this problem. I am putting our findings here in case anyone else stumbles across this question like I did.
Our configuration:
Host A: IP address 192.168.0.1, netmask 255.255.255.0
Host B: IP address 192.168.1.1, netmask 255.255.254.0
Neither host has a default gateway.
We are connecting from Host B to Host A. (That is not a typo.) The connect call succeeds, but when we try to send data, we get errno 113 aka. EHOSTUNREACH aka. "No route to host".
The fix, of course, was to change the subnet on Host A to match Host B.
We were surprised to see this error on a connection within the same subnet / same LAN. And we were surprised that connect succeeded followed by send failing. And we were surprised to see this error on Host B even though the network configuration on Host B itself was fine.
Somehow, the incorrect subnet on Host A caused this error on Host B...
...and just like that, today I learned about ICMP "destination unreachable" messages.

Raspberry PI Server/Client Socket in Python

I am trying to set up a Python socket between my Raspberry Pi (running Raspbian) and my Macbook Pro (running Mavericks).
Both devices are connected to the same WiFi network in my appt. I run the server code on my RPi and then the client code on my Macbook (I have also tried the reverse). I think that I am missing a set up step because the code I am using I found on multiple sites, so I assume it works. I also checked that my Macbook has firewall turned off.
Server Code:
from socket import *
host = "127.0.0.1"
print host
port = 7777
s = socket(AF_INET, SOCK_STREAM)
print "Socket Made"
s.bind((host,port))
print "Socket Bound"
s.listen(5)
print "Listening for connections..."
q,addr = s.accept()
data = raw_input("Enter data to be sent: ")
q.send(data)
Client Code:
from socket import *
host = "127.0.0.1"
print host
port=4446
s=socket(AF_INET, SOCK_STREAM)
print "socket made"
s.connect((host,port))
print "socket connected!!!"
msg=s.recv(1024)
print "Message from server : " + msg
I get the error:
Traceback (most recent call last):
File "TCPclient.py", line 9, in <module>
s.connect((host,port))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py",
line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 61] Connection refused
My process for executing the code is:
type "python TCPserver.py" into RPi terminal
type "python TCPclient.py into Macbook terminal
Then I receive the error message on my Macbook, no error on the RPi
My questions are:
Is 127.0.0.1 the proper input for "host"? (please note I also tried "localhost")
Does the input for host have to be the same for the client and server code?
Should the RPi and Macbook both be connected to the same WiFi network?
Is there any set up that needs to be done on either the RPi or my Macbook in order for this to work (Please note my RPi is Model B, new, and I did not set up anything else on it before this)
Do you know why I am receiving this error and how to fix it?
Your help is greatly appreciated!!
127.0.0.1 is a special IP address for local machine.
You must set the real IP address (on your LAN) of you mac in the client code.
You should also bind on this IP on the server, or on 0.0.0.0 to bind on all available IP addresses.
You must also use the same port number on both client and server.
And to reply to your questions:
Is 127.0.0.1 the proper input for "host"? (please note I also tried "localhost")
127.0.0.1 is the same than localhost, it means the local machine. This will work if you run the client and the server on the same machine, else you need the real IP address of your mac. Try ifconfig in a console.
Does the input for host have to be the same for the client and server code?
Yes and no. On the server you bind to a port and an address, so you'll wait for connections on this port and address. You can use the IP address, or 0.0.0.0.
Should the RPi and Macbook both be connected to the same WiFi network?
Yes and no. It will work with the same WiFi network, but it will also work with two different WiFi networks if they are connected together directly or with a IP router. Most of the time though they are connected to the internet through a NAT (network address translator), and then it will not work.
Is there any set up that needs to be done on either the RPi or my Macbook in order for this to work (Please note my RPi is Model B, new, and I did not set up anything else on it before this)
I don't know much about the RPi but it looks like standard TCP sockets, that should work out of the box.
Do you know why I am receiving this error and how to fix it?
As I stated at the beginning: You try to connect to the RPi (127.0.0.1) on the wrong port.
You have created a listener on port 7777, then you connected on 4446 !!!!!
just connect on the same port you are listening to =)

Categories