5 import avahi, dbus, gobject, sys, getopt
12 def usage(retval = 0):
13 print "%s [options] <name> <type> <port> [<txt> ...]\n" % sys.argv[0]
14 print " -h --help Show this help"
15 print " -d --domain Domain where to register this service"
16 print " -H --host Host where this service resides"
20 opts, args = getopt.getopt(sys.argv[1:], "d:H:", ["help", "domain=", "host="])
21 except getopt.GetoptError:
28 if o in ("-h", "--help"):
31 if o in ("-d", "--domain"):
34 if o in ("-H", "--host"):
38 sys.stderr.write("Invalid number of arguments\n")
46 # python-dbus doesn't allow transmission of empty arrays, therefore we "fix" it with a bogus entry
48 txt.append("python-dbus=brain-damage")
56 if not (group is None):
61 global server, group, name, stype, domain, host, port, txt
64 print "Adding service '%s' of type '%s' ..." % (name, stype)
65 group = dbus.Interface(bus.get_object(avahi.DBUS_NAME, server.EntryGroupNew()), avahi.DBUS_INTERFACE_ENTRY_GROUP)
66 group.connect_to_signal('StateChanged', entry_group_state_changed)
67 group.AddService(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, name, stype, domain, host, dbus.UInt16(port), txt)
70 def entry_group_state_changed(state):
71 global name, server, n_rename
73 if state == avahi.ENTRY_GROUP_ESTABLISHED:
74 print "Service established."
75 elif state == avahi.ENTRY_GROUP_COLLISION:
77 n_rename = n_rename + 1
79 print "ERROR: No suitable service name found after %i retries, exiting." % n_rename
82 name = server.GetAlternativeServiceName(name)
83 print "WARNING: Service name collision, changing name to '%s' ..." % name
87 def server_state_changed(state):
88 if state == avahi.SERVER_COLLISION:
89 print "WARNING: Server name collision"
91 elif state == avahi.SERVER_RUNNING:
94 main_loop = gobject.MainLoop()
96 bus = dbus.SystemBus()
97 server = dbus.Interface(bus.get_object(avahi.DBUS_NAME, avahi.DBUS_PATH_SERVER), avahi.DBUS_INTERFACE_SERVER)
98 server.connect_to_signal("StateChanged", server_state_changed)
99 server_state_changed(server.GetState())
103 except KeyboardInterrupt, k: