pythonsocketslinux-kernelmulticastigmp

How to send igmp join from specific interface with python ?


i'm trying to implement the following program in Python to send join request from a specific interface (right now my kernel is choosing something by default).

 import socket
 import struct
 import time  
 MCAST_GRP = '239.0.1.1' 
 MCAST_PORT = 2000      
 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)  
 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 
 sock.bind((MCAST_GRP, MCAST_PORT)) 
 mreq = struct.pack("4sl", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY) 
 sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

i was trying to change the socket.INADDR_ANY to socket.inet_aton('X.X.X.X') when X.X.X.X is my interface ip address represent by a string, but i got an error.

Any way what can i do to make it work?

Thanks, Talor


Solution

  • found the answer: need to change "4sl" to "4s4s" and express the interface that i want to send the igmp join request as a four-bytes string. i can write the code as follow:
    interface = '168.152.63.15' mreq = struct.pack("4s4s", socket.inet_aton(MCAST_GRP), socket.inet_aton(interface))