The code:
import socket, threading
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("my ipv4 from ipconfig", 12))
server.listen(5)
def client_handler(client_socket):
request = client_socket.recv(100)
print "[*] Received: " + request
client_socket.close()
while True:
client, addr = server.accept()
print "[*] Accepted connection from: %s:%d" % (addr[0], addr[1])
servert = threading.Thread(target=client_handler, args=(client,))
servert.start()
So the server seems to work fine locally but if i ask my friend on a different network to connect, it doesn't connect. I tried port forwarding from the router
http://i.stack.imgur.com/wSUir.png ( cant post img apparently cause my_reputation < 10)
I also tried using the ip i get from the whatismyip website, but i get the error:
error: [Errno 10049] The requested address is not valid in its context
Any ideas on what i could do so other people can connect? Thanks.
When you're trying to access your server from outside your LAN, you ought to use 0.0.0.0 as your IP address while creating your socket object. 0.0.0.0 usually means the default route (the route to "the rest of" the internet, aside from routes in your local network etc.). If you use the IP address allotted by DCHP (in your case, the router), the devices connected to the network (router) is only aware of the fact that your IP address is what you get in $ifconfig command, a private IP address which the client is unaware
Related
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)
I'm making a chat app using sockets in python, but when I try to connect from a different computer then it says:
C:\Users\James\OneDrive\Documents\Python\Projects\Gui Chat\client.pyw
[WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
This is the server code for the socket:
host = socket.gethostbyname(hostname)
port = 55555
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
print(f"IP: {server.getsockname()[0]}\nPORT: {server.getsockname()[1]}")
server.listen()
I also have a while True loop accepting all requests:
while True:
client, address = server.accept()
print(f"Connected with {str(address)}")
On the client end this is the socket code:
IP = simpledialog.askstring("IP", "Enter IP address", parent=root) # "192.168.1.252" # input("Enter IP: ")
nickname = simpledialog.askstring("Nickname", "Choose a nickname", parent=root)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
client.connect((IP, 55555))
except Exception as e:
print(e)
The programme asks for the IP address each time, and when I put in the correct IP for the server computer, it comes up with the error above. It works if I try to connect from the same computer, and they are both on the same network. It was working recently, and now it has just stopped working.
UPDATE:
I have set the server ip to 0.0.0.0, I have set up a port forwarding rule, I have checked the firewall and allowed incoming and outgoing connections, and I have run nmap with these results:
Code issues
First try binding server on localhost or 127.0.0.1.
FireWall/Ports issues
Check if your computer's default computer/antivurus
firewall (where server is hosted) allow connections
on your port 55555.
And if computer with client is outside your home network
point to router public IP address and make sure you have
port forwarding setup on router.
Address issues
Are you sure that IP you are writing in client is correct.
Go to your computer with server and check that IP.
Windows:
Go to cmd or Power Shell and type ipconfig, then find
section IPv4 Address and look that address you habe there.
Linux / MacOS
Go to your terminal and type ifconfig -a, and
it should be somewhere there, but I don't have those systems,
so I can't test it for you. If it does't work try to search how to
find that out.
[WinError 10061] and [WinError 10060]. These are the errors im getting when i send a client app to my friend. Remotely it just doesn't work. Locally it works fine. Can i get a full explanation step by step please cause i couldn't find any soulution and i'm getting mad.
SERVER:
import socket as s
HOST = 'ppp.ppp.p.ppp'
PORT = 33000
server_socket = s.socket(s.AF_INET, s.SOCK_STREAM)
server_socket.bind((HOST, PORT))
server_socket.listen()
while True:
client_socket, address = server_socket.accept()
print(f'Connected {address}')
CLIENT:
import socket as s
HOST = 'ppp.ppp.p.ppp'
PORT = 33000
client_socket = s.socket(s.AF_INET, s.SOCK_STREAM)
client_socket.connect((HOST, PORT)) # here is error
PS: CLIENT GETS ERRORS NOT SERVER
welcome to SO. You and your friend are probably not on the same network. Therefore, when sending a connection request, your router (or your friends) does not know to relay the packet to the correct device in it's network. There are multiple things you need to do:
Make sure that the IP is not your local network IP but rather the IP of your router. check on wahtismyip. Use that as the ip. Note that the ip will change every so often.
Then, the difficult part. You need to tell your router (or your friends if the server is in his network) to relay the packets arriving at port 33000 to the server. This is different from device to device, try googling "Port forwarding ".
Hopefully this resolves your issues.
I am new to Socket Programming. I have implemented the client and server script for transferring the file over internet. Both scripts are working on Local Area Network computers. I have tried to exchange the files in Local area network from 1MB to 1GB, the scripts are running fine.
But When I am using both the script to work on different network means internet. It's not working. I have checked the firewall rules of both system. Python is allowed. Here is the code snippet. Can someone tell me what is the problem ?
Script -> Server.py
import os
import socket
file_path = r'C:\Users\Baby\Downloads\006.jpg'
file_size = str(os.path.getsize(file_path))
file_name = file_path.split('\\')[-1]
# print file_name.encode('UTF-8')
total = file_name+ '/'+file_size
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host = socket.gethostbyname(socket.gethostname())
# value of host = '103.235.165.205' as this is my ip which i am using in client.py
s.bind((host,21000))
s.listen(5)
print 'Server is listening on {}:21000'.format(host)
conn,addr = s.accept()
print 'Got connection from IP :{} Host :{}'.format(addr[0],addr[1])
conn.send(total.encode())
with open(file_path,'rb') as data:
while data:
conn.send((data.read()))
break
conn.close()
print 'transfer complete'
s.close()
Script -> Client.py
import socket
s = socket.socket()
s.connect(('10.174.238.205',21000))
total = (s.recv(1024)).decode()
file_name , file_size = map(str,total.split('/'))
data = s.recv(int(file_size.decode()))
with open(file_name,'wb') as getfile:
getfile.write(data)
Each network adapter in the server should be associated with its own iP address.
The s.bind() command should use the IP or host name associated with the network adapter on which you wish to listen for a connector. This should be an adapter attached to the network on which the clients are running.
Also if the connection is going out side the local network, you must be using an IP that is publicly visible. You can read about IP assignments here and many other places (Google is your friend). Normally public IP addresses will be assigned by your ISP (sometimes for additional cost since they are a scarce resource.)
Thanks to #jasonharper for pointing out the public vs private IP issue in a comment.
Title says all. I have a client and a server setup, but they only work with localhost. How can I connect to the socket from a different network?
Client
# Echo client program
import socket
print "Client"
HOST = "localhost" # Symbolic name meaning all available interfaces
PORT = 5001
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST,PORT))
while True:
data2 = raw_input()
s.sendall(data2)
Server
# Echo server program
import socket
print "Server"
HOST = "" # Symbolic name meaning all available interfaces
PORT = 5001 # 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)
print data
if data == "Ping":
print "Pong!"
conn.close()
Check your public ip address using online tools like http://whatismyipaddress.com/
Check your local ip address using ipconfig -a in windows ifconfig in linux.
Now if you are behind a dsl router (generally, you are) these addresses are completely different. So you have to tell your router to send whenever a connection attemp received to a TCP port XXXX , forward it to "My Machine" (called Port Forwarding ). Although port forwarding settings are similar in most routers, there is no standard (Generally under NAT / Port Forwarding menu items on your router web configuration interface ). You may have to search instructions for your specific model.It's a good idea to set your computer to use a static ip address before port forwarding.Otherwise, the settings will be invalid if your computer is assigned another IP adress via DHCP.
If port forwarding is successful, now you only have to set your client application to connect to your public ip address. In your specific situation it's HOST = "X.X.X.X" in your client source code. Check if port forwarding works with a socket tester application you downloaded from somewhere. ( Don't test it with your experimental code, use an application you are sure that it's working). All did not work, check out the note below. It's the last resort ,though.
Note : Some ISP's put their clients behind an extra firewall for security. A simple method to detect if this is the situation is , your Wan ip address you see in your router web interface will be different from what you see in online tools like whatsmyip. In this situation no matter what you do , you will not be able to connect. You have to call your ISP and tell them to disable firewall for your connection . You may have some difficulties to explain them what you are talking about :).