Jilin
Jilin

Reputation: 321

python socket connecting to different subnet/domain

Is it possible to connect to a different subnet or domain by python socket programming?

I want to make a script for sharing files with friends,, but currently I only know how to connect within one LAN.

Upvotes: 0

Views: 1923

Answers (1)

Robert Lu
Robert Lu

Reputation: 2199

in LAN, you should broadcast packets to discover each other.
and every peer should listen the port to receive broadcast.

It is discovery protocol, you can implement it by UDP socket.

Once two peer decide to communicate, they should create a TCP socket. Then, they can send data via TCP.
Or you can use HTTP, XML-RPC etc. to transfer data(not broadcast, TCP is not support broadcast).


#udp broadcast
import socket, time

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

while True:
    data = 'test'.encode()
    s.sendto(data, ('255.255.255.255', 1080))
    time.sleep(1)

#udp receive broadcast
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('', 1080))

while True:
    print(s.recv(1024))

Upvotes: 1

Related Questions