简体   繁体   中英

Python 2.7 Socket connection on 2 different networks?

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()
  1. Check your public ip address using online tools like http://whatismyipaddress.com/
  2. 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 = "XXXX" 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 :).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM