register.py 1.86 KB
O'Reilly Media, Inc. committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
#!/usr/bin/python
#
# Bonjour register example
#
# Usage: python register.py <serviceName> <serviceType> <port>
#
# e.g. python register.py myservice _myservicetype._tcp 12345

import sys
import time
import bonjour
import select
import socket

def RegisterCallback(sdRef, flags, errorCode, name, regtype, domain, context):
    print "Service registered:", name, regtype, domain

if len(sys.argv) < 4:
    print "Usage: register.py servicename regtype port"
    sys.exit(1)

servicename = sys.argv[1]
regtype = sys.argv[2]
port = int(sys.argv[3])

# Allocate a service discovery reference and register the specified service
serviceRef = bonjour.AllocateDNSServiceRef()
ret = bonjour.pyDNSServiceRegister(
    serviceRef,           # DNSServiceRef           *sdRef,
    0,                    # DNSServiceFlags         flags,         /* may be 0 */
    0,                    # uint32_t                interfaceIndex,/* may be 0 */
    servicename,          # const char              *name,         /* may be NULL */
    regtype,              # const char              *regtype,
    "",                   # const char              *domain,       /* may be NULL */
    "",                   # const char              *host,         /* may be NULL */
    port,                 # uint16_t                port,
    0,                    # uint16_t                txtLen,
    "",                   # const void              *txtRecord,    /* may be NULL */
    RegisterCallback,     # DNSServiceRegisterReply callBack,      /* may be NULL */
    None)

if ret != bonjour.kDNSServiceErr_NoError:
    print "error %d returned; exiting" % ret
    sys.exit(ret)

# Get the socket and loop
fd = bonjour.DNSServiceRefSockFD(serviceRef)
while 1:
    ret = select.select([fd], [], [])
    ret = bonjour.DNSServiceProcessResult(serviceRef)

# Deallocate the service discovery ref
bonjour.DNSServiceRefDeallocate(serviceRef)