
#include     "./include/iptrans.h"

/*@ignore@*/
int
mcast_join(int sockfd, struct sockaddr *sa, socklen_t salen,
           const char *ifname,u_int ifindex)
{
   //u_char flag=1;
   //int len;
   //struct hostent *myhost;

   switch(sa->sa_family)
  {
   case AF_INET:{
     struct ip_mreq mreq;
     struct ifreq ifreq;
     memcpy(&mreq.imr_multiaddr,
            &((struct sockaddr_in *)sa)->sin_addr,
            sizeof(struct in_addr));
     if(ifindex>0){
       if(if_indextoname(ifindex,ifreq.ifr_name)==NULL){
         // errno=ENXIO;
          return(-1);
       }
       goto doioctl;
     } 
     else if(ifname !=NULL){
       strncpy(ifreq.ifr_name,ifname,IFNAMSIZ);
     doioctl:
       if(ioctl(sockfd,SIOCGIFADDR,&ifreq)<0)
         return (-1);
       memcpy(&mreq.imr_interface.s_addr,
	      &((struct sockaddr_in *)&ifreq.ifr_addr)->sin_addr,
             sizeof(struct in_addr));
       return (setsockopt(sockfd,IPPROTO_IP,IP_ADD_MEMBERSHIP,
             &mreq,sizeof(mreq)));
     }
     else  
       mreq.imr_interface.s_addr=htonl(INADDR_ANY);// inet_addr(name);
//     setsockopt(sockfd,IPPROTO_IP,IP_MULTICAST_IF,&flag,sizeof(flag));
       return (setsockopt(sockfd,IPPROTO_IP,IP_ADD_MEMBERSHIP,
             &mreq,sizeof(mreq)));
    }
    default:
     // errno=EPROTONOSUPPORT;
      return(-1);
    }
} 
     		
int 
mcast_set_loop(int sockfd, int onoff)
{
  u_char flag;
  flag=onoff;
  return (setsockopt(sockfd,IPPROTO_IP,IP_MULTICAST_LOOP,
          &flag,sizeof(flag)));
}
/*@end@*/
