Python service discovery: Advertise a service across a local network

后端 未结 1 453
感动是毒
感动是毒 2021-02-01 07:21

I have a \"server\" python script running on one of the local network machines, which waits for clients to connect, and passes them some work to do. The server and client code h

相关标签:
1条回答
  • 2021-02-01 08:05

    An easy way to do service announcement/discovery on the local network is by broadcasting UDP packets.

    Constants:

    PORT = 50000
    MAGIC = "fna349fn" #to make sure we don't confuse or get confused by other programs
    

    Announcement:

    from time import sleep
    from socket import socket, AF_INET, SOCK_DGRAM, SOL_SOCKET, SO_BROADCAST, gethostbyname, gethostname
    
    s = socket(AF_INET, SOCK_DGRAM) #create UDP socket
    s.bind(('', 0))
    s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) #this is a broadcast socket
    my_ip= gethostbyname(gethostname()) #get our IP. Be careful if you have multiple network interfaces or IPs
    
    while 1:
        data = MAGIC+my_ip
        s.sendto(data, ('<broadcast>', PORT))
        print "sent service announcement"
        sleep(5)
    

    Discovery:

    from socket import socket, AF_INET, SOCK_DGRAM
    
    s = socket(AF_INET, SOCK_DGRAM) #create UDP socket
    s.bind(('', PORT))
    
    while 1:
        data, addr = s.recvfrom(1024) #wait for a packet
        if data.startswith(MAGIC):
            print "got service announcement from", data[len(MAGIC):]
    

    This code was adapted from the demo on python.org

    0 讨论(0)
提交回复
热议问题