python-zeroconf 纯python 实现的mdns 工具包

python-zeroconf 是基于python 实现的mdns 工具包,可以实现mdns的服务注册,服务发现

参考使用

一个简单示例,基于mdns 暴露一个nginx服务为myapp.local

#!/usr/bin/env python

"""Example of announcing a service (in this case, a fake HTTP server)"""

import argparse
import logging
import socket
from time import sleep

from zeroconf import IPVersion, ServiceInfo, Zeroconf

if __name__ == "__main__":
    logging.basicConfig(level=logging.DEBUG)

    parser = argparse.ArgumentParser()
    parser.add_argument("--debug", action="store_true")
    version_group = parser.add_mutually_exclusive_group()
    version_group.add_argument("--v6", action="store_true")
    version_group.add_argument("--v6-only", action="store_true")
    args = parser.parse_args()

    if args.debug:
        logging.getLogger("zeroconf").setLevel(logging.DEBUG)
    if args.v6:
        ip_version = IPVersion.All
    elif args.v6_only:
        ip_version = IPVersion.V6Only
    else:
        ip_version = IPVersion.V4Only

    desc = {"path": "/~paulsm/"}

    info = ServiceInfo(
        "_http._tcp.local.",
        "Paul's Test Web Site._http._tcp.local.",
        addresses=[socket.inet_aton("192.168.196.1")],
        port=80,
        properties=desc,
        server="myapp.local.",
    )

    zeroconf = Zeroconf(ip_version=ip_version)
    print("Registration of a service, press Ctrl-C to exit...")
    zeroconf.register_service(info)
    try:
        while True:
            sleep(0.1)
    except KeyboardInterrupt:
        pass
    finally:
        print("Unregistering...")
        zeroconf.unregister_service(info)
        zeroconf.close()

说明

mdns 还是比较方便的,macos 中部分都是用了此服务,同时鸿蒙系统也是支持的,同时在不少iot 开发中也有使用到

参考资料

https://github.com/python-zeroconf/python-zeroconf

https://developer.huawei.com/consumer/cn/doc/atomic-guides-V5/atomic-net-mdns-V5

posted on 2025-05-04 08:00  荣锋亮  阅读(175)  评论(0)    收藏  举报

导航