2012-03-11 2 views
3

나는 파이썬에 zmq 바인딩을 사용하고 있으며, 클라이언트를 일부 포트에 바인드하고 그 위치를 다른 클라이언트에 연결하여 연결하려고합니다.0mq 바인드 된 주소를 얻는 방법

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

내가 뭘 얻을 필요하면 외부 주소하지 0.0.0.0입니다 : 지금이 기본 바인딩 코드입니다. 내 PC가 ip 192.168.1.10을 가지고 있다고 가정 해 봅시다. "tcp : //192.168.1.10 : 12345"를 가져 와서 "tcp : //0.0.0.0 : 12345"를 보내면 다른 클라이언트에게 보내야합니다. 쓸모가 없습니다. 소켓을 생성하기 위해 zmq가 사용했던 인터페이스의 외부 IP를 얻으려면 어떻게해야합니까? PC에 NIC의 번호가있을 수 있으며, 정상적인 소켓을 사용하여 외부 IP를 얻으려고하면 잘못된 것일 수 있습니다. 왜냐하면 어떤 NIC zmq를 사용했는지 모르기 때문입니다.

답변

1

0.0.0.0 (INADDR_ANY)은 "임의"주소 (라우팅 할 수없는 메타 주소)입니다. "모든 IPv4 인터페이스를 지정하는"방법입니다.

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 
: 이것은 모든 인터페이스는 모든 네트워크 인터페이스를 나열하려면

포트 12345에 듣고 난 당신이 리눅스를 사용하는 경우이 작업을 수행 할 수 this

같은 라이브러리를 사용하는 것이 좋습니다 것을 의미

관련 문제