【问题标题】:ZeroMQ how to get binded address in pyzmqZeroMQ如何在pyzmq中获取绑定地址
【发布时间】:2012-03-11 23:49:51
【问题描述】:

我在 Python 中使用 ZMQ 绑定,我想将客户端绑定到某个端口,然后将该位置发送给其他客户端进行连接。 现在这是基本的绑定代码:

subscriber = context.socket(zmq.SUB)
...
subscriber.bind("tcp://0.0.0.0:12345")

我需要获取的是外部地址,而不是0.0.0.0,假设我的电脑有IP 192.168.1.10,我需要获取“tcp://192.168.1.10:12345”并将其发送给其他客户端,因为发送tcp://0.0.0.0:12345 是没用的。

如何获取 ZMQ 用于创建套接字的接口的外部 IP?

pc上可以有网卡的数量,如果我只是尝试使用普通socket获取外部IP可能是无效的,因为我不知道ZMQ用的是什么网卡。

【问题讨论】:

    标签: python sockets zeromq pyzmq


    【解决方案1】:

    0.0.0.0 (INADDR_ANY) 是“任何”地址(不可路由的元地址)。这是一种指定“任何 IPv4 接口”的方法。 这意味着您的所有接口都在侦听端口 12345。

    要列出所有网络接口,我建议使用 this 之类的库

    如果您使用的是 linux,您可以这样做:

    import array
    import struct
    import socket
    import fcntl
    
    SIOCGIFCONF = 0x8912  #define SIOCGIFCONF
    BYTES = 4096          # Simply define the byte size
    
    # get_iface_list function definition 
    # this function will return array of all 'up' interfaces 
    def get_iface_list():
        # create the socket object to get the interface list
        sck = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    
        # prepare the struct variable
        names = array.array('B', '\0' * BYTES)
    
        # the trick is to get the list from ioctl
        bytelen = struct.unpack('iL', fcntl.ioctl(sck.fileno(), SIOCGIFCONF, struct.pack('iL', BYTES, names.buffer_info()[0])))[0]
    
        # convert it to string
        namestr = names.tostring()
    
        # return the interfaces as array
        return [namestr[i:i+32].split('\0', 1)[0] for i in range(0, bytelen, 32)]
    
    # now, use the function to get the 'up' interfaces array
    ifaces = get_iface_list()
    
    # well, what to do? print it out maybe... 
    for iface in ifaces:
     print iface
    

    【讨论】:

      【解决方案2】:

      要获取您机器的 IP 地址,这可能会有所帮助:

      def get_ip_data(ether_adapter):
          ip_data = os.popen("ifconfig " + ether_adapter)
          for line in ip_data:
              match2 = re.search(r'inet addr:+(\d+.\d+.\d+.\d+)', line)
              if match2:
                  ip_ = match2.group(1)
                  return ip_
      if __name__=="__main__":
          ethernet_card = "wlp3s0"   ---> This might be etho or whatever you want
          ip_of_the_machine = get_ip_data(ethernet_card)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多