简体   繁体   中英

How to establish a connection between two devices in the same network with PYTHON SOCKETS?

Im currently learning how do python sockets work, and I'd love to know, how to establish a connection between two devices that are in the same local network.

I currently know how to establish a connection between two processes using the loopback interface:

CLIENT:

import socket


s = socket.socket()
port = 9999
s.connect(('127.0.0.1', port))
print(s.getsockname()[1])
print(s.recv(1024).decode())
s.close()

SEVER:

import socket



try: 
    s = socket.socket()
    print ("Socket successfully created")
except socket.error as err: 
    print("Socket creation failed with error: ")
    print(err)
    exit()


s.bind(('', 9999))
s.listen(5)

print("Listening on port", s.getsockname()[1], "...\n\n")

while True:
    c, addr = s.accept()
    print("Connection from:", addr)
    res = input()
    c.send(res.encode())
    c.close()
    if res == "bye":
        break

Please help.

change s.bind(('', 9999)) to s.bind(('0.0.0.0', 9999))

now you can connect as your local ip in your client

s.connect(('192.168.1.132', port))

I'm sorry community.

Looks like, I just needed to establish a connection using the local ip of the host that runs the server.

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