4

I'm using ZMQ bindings in Python, and I want to bind clients to some port, and then send that location to other clients to connect. Now this is basic binding code:

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

What I need to get is external address, not 0.0.0.0, let say my pc has IP 192.168.1.10, I need to get "tcp://192.168.1.10:12345" and send that to other clients, because sending tcp://0.0.0.0:12345 is useless.

How can I get external IP of interface that ZMQ used to create a socket?

There can be the number of NIC on pc, and if I just try to get external IP using normal socket it could be invalid, cause I don't know what NIC ZMQ used.

Benyamin Jafari
  • 27,880
  • 26
  • 135
  • 150
Bojan Radojevic
  • 1,015
  • 3
  • 16
  • 26

2 Answers2

1

0.0.0.0 (INADDR_ANY) is the "any" address (non-routable meta-address). It is a way to specify "any IPv4-interface at all". This means that all your interfaces are listening on port 12345.

To list all your network interfaces I would recommend to use a library like this

If you are using linux you could do this:

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
Schildmeijer
  • 20,702
  • 12
  • 62
  • 79
0

To get the IP address of your machine, this might help:

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)
Benyamin Jafari
  • 27,880
  • 26
  • 135
  • 150
KSp
  • 1,199
  • 1
  • 11
  • 29