Multicast socket

Benoit BESSE benoit.besse at club-internet.fr
Wed Jun 18 02:10:26 EDT 2003


Hello, my script try to multicast message over the net but I have this error

C:\Python21\_projet>python mcast2.py -s
Traceback (most recent call last):
  File "mcast2.py", line 202, in ?
    main()
  File "mcast2.py", line 195, in main
    sender(flags[0])
  File "mcast2.py", line 103, in sender
    mcastSocket.setsockopt(IPPROTO_IP,IP_ADD_MEMBERSHIP, mreq)
  File "<string>", line 1, in setsockopt
socket.error: (10055, 'No buffer space available')

Here my script. Please try a very bad french pythonner. Thanks.

BB

# Send/receive UDP multicast packets.
# This is built-in on SGI, still optional for most other vendors.
# Usage:
#   mcast -s (sender)
#   mcast -b (sender, using broadcast instead multicast)
#   mcast    (receivers)
MYPORT = 9875
MYGROUP = '127.0.0.0'
TTL = 1
import struct, MySQLdb, sys, time
import re, string
from NetworkTimeProtocolConvert import *
from socket import *
############################################################################
#########################################
# Initialise la connection a la base de donnees
############################################################################
#########################################
def OpenConnection(self, host="localhost",
user="root",passwd="",db="ZCONF"):
 """Initialise la connection a la base de donnees"""
 host=host
 user=user
 passwd=passwd
 db=db
 connex,cursor,erreur="","",""
 try:
  connex = MySQLdb.connect(host,user,passwd,db)
  cursor = connex.cursor()
 except MySQLdb.Error, erreur:
  print "Erreur ouverture cursor et connection %d: %s" % (erreur.args[0],
erreur.args[1])
 return connex,cursor,erreur
############################################################################
#########################################
# Ferme le curseur et la connection a la base de donnees
############################################################################
#########################################
def CloseConnection(connex,cursor):
 """Ferme le curseur et la connection a la base de donnees"""
 erreur=""
 try:
  cursor.close ()
  connex.close ()
 except MySQLdb.Error, erreur:
  print "Erreur fermeture cursor et connection %d: %s" % (erreur.args[0],
erreur.args[1])
 return erreur
############################################################################
#########################################
# Selection d'une session dans la table des sessions a emettre
############################################################################
#########################################
def SelectSession():
 """Selection d'une session dans la table des sessions a emettre"""
 erreur,requete,data="","",""
 nbrlgn=0
 connex,cursor,errcon=OpenConnection("")
 try:
  requete  = "SELECT
id_ts,ts_name,ts_info,ts_ddebut,ts_hdebut,ts_dfin,ts_hfin,ts_repetition,"
  requete +=       " user_id,id_lieux,liste_media"
  requete += " FROM temp_session"
 except:
  f.write("!!! Erreur requete SELECT dans la table SAP !!! "+LF+requete+LF)
 try:
  cursor.execute(requete)
  nbrlgn = int(cursor.rowcount)
  try:
   data=cursor.fetchall()
  except MySQLdb.Error, erreur:
   f.write("Erreur session     FETCH %d: %s" % (erreur.args[0],
erreur.args[1])+LF)
 except MySQLdb.Error, erreur:
  f.write("Erreur session     SELECT %d: %s" % (erreur.args[0],
erreur.args[1])+LF)
 errcon=CloseConnection(connex,cursor)
 return data,erreur,nbrlgn
############################################################################
#########################################
# Formate un message SDP
############################################################################
#########################################
def MessageSDP(Session):
    "Retourne "
    uri="http://benoit.the.best.net"
    msg = "v=0\r\n" + \
          "o="+str(Session['id_ts'])+ntpTime() + " " + ntpTime() + " IN IP4
sphinx.via.ecp.fr\r\n" + \
          "s=" + Session['ts_name'] + "\r\n" + \
          "u=" + uri + "\r\n" + \
          "t=0 0\r\n" + \
          "c=IN IP4 127.0.0.1/1\r\n" + \
          "m=video 1234 RTP/MP2T 33\r\n" + \
          "a=control:" + uri + "\r\n"
    return msg
############################################################################
#########################################
# Envoie de données sur un groupe multicast
############################################################################
#########################################
def sender(flag):
 Session={}
 mcastSocket = socket(AF_INET, SOCK_DGRAM)
 if flag == '-b':
  mcastSocket.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
  mygroup = '<broadcast>'
 else:
         mygroup = MYGROUP
# set time-to-live option on the socket
  if sys.platform == "win32":
          mcastSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
          mcastSocket.setblocking(0)
   mcastSocket.bind( ("", MYPORT))
          ttl = struct.pack( 'I', TTL )
# Construct struct mreq from grpaddr and ifaddr
   ifaddr = INADDR_ANY
   mreq = struct.pack('>4sl',address_to_bytes(mygroup), ifaddr)
# Add group membership
   mcastSocket.setsockopt(IPPROTO_IP,IP_ADD_MEMBERSHIP, mreq)
# following shouldn't be necessary, as loop back isthe default
   mcastSocket.setsockopt(IPPROTO_IP, IP_MULTICAST_TTL,ttl)
  else:
   ttl = struct.pack('B', TTL )
   mcastSocket.setsockopt(IPPROTO_IP, IP_MULTICAST_TTL,ttl)
 while 1:
  print 'sending'
  data,erreur,nbrlgn=SelectSession()
  print data
  for record in data:
   Session['id_ts']=record[0]
   Session['ts_name']=record[1]
   Session['ts_info']=record[2]
   Session['ts_ddebut']=record[3]
   Session['ts_hdebut']=record[4]
   Session['ts_dfin']=record[5]
   Session['ts_hfin']=record[6]
   Session['ts_repetition']=record[7]
   Session['user_id']=record[8]
   Session['id_lieux']=record[9]
   Session['liste_media']=record[10]
   print "record[0]",record[0]
   print "record[1]",record[1]
   print "Session",str(Session)
   Message = MessageSDP(Session)
   print Message
  #mcastSocket.sendto(record[0], (mygroup, MYPORT))
         try:
             data = mcastSocket.recvfrom(1500)
             print 'got data', data
         except:
             pass
         time.sleep(5)
############################################################################
#########################################
# Passe une adresse en bit
############################################################################
#########################################
def address_to_bytes( address ):
    bytes = map(chr,map(string.atoi,string.split(address,'.',),))
    return string.join(bytes, "")
############################################################################
#########################################
# Ouvre et initialise une socket et écoute un groupe multicast
############################################################################
#########################################
def receiver():
# Open and initialize the socket
    mcastSocket = openmcastsock(MYGROUP, MYPORT)
    print MYGROUP, MYPORT, str(mcastSocket)
# Loop, printing any data we receive
    while 1:
        try:
            data, sender = mcastSocket.recvfrom(1500)
            while data[-1:] == '\0':
                data = data[:-1] # Striptrailing \0's
                print sender, ':', `data`
        except error, value:
            if value.args[0] == 10035:
                pass
            else:
                raise
                time.sleep( 0.05)
############################################################################
#########################################
# Ouvre une socket UDP, la bind sur le port et selectionne une group
multicast
############################################################################
#########################################
# Open a UDP socket, bind it to a port and select a multicast group
def openmcastsock(group, port):
# Import modules used only here
    import struct
# Create a socket
    mcastSocket = socket(AF_INET, SOCK_DGRAM)
    mcastSocket.setblocking( 0)
# Allow multiple copies of this program on one machine
    mcastSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
# Bind it to the port
    mcastSocket.bind(('', port))
# Look up multicast group address in name server
    group = gethostbyname(group)
# Construct struct mreq from grpaddr and ifaddr
    ifaddr = INADDR_ANY
    mreq = struct.pack('>4sl', address_to_bytes(group), ifaddr)
    print `mreq`
# Add group membership
    mcastSocket.setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP, mreq)
    return mcastSocket
############################################################################
#########################################
# Procedure principale : execute un serveur ou donne usage du module
############################################################################
#########################################
def main():
 global f, fic
 f=open('SessionCreate.txt', 'w')
 fic=open('Enreg.txt', 'w')
 flags = sys.argv[1:]
 if flags:
  sender(flags[0])
 else:
  receiver()
############################################################################
#########################################
# Point d'entree du module
############################################################################
#########################################
if __name__=="__main__":
    main()






More information about the Python-list mailing list