/************************** * UDP Server Dependency * *************************** * Designed & Developed by * * Adrien Marquès * * * *************************** * doowap31@gmail.com * **************************/ #include "server.h" int DROP_UDP_SERVER(in_addr_t pAddr, const int pPort, int* pListenSock, struct sockaddr_in* pInfo, const char pMcast){ if( DEBUGMOD&HDR ) printf("====== DROP_UDP_MCAST(%x, %d, %p, %p, %d) ======\n\n", pAddr, pPort, (void*) pListenSock, (void*) pInfo, (int) pMcast); /* [0] Initialisation des variables =========================================================*/ int STATUS; // status struct ip_mreq mcastReq; *pListenSock = -1; struct in_addr tmp; /* [1] Création de la socket =======================================================*/ /* 1. Création socket */ *pListenSock = socket(AF_INET, SOCK_DGRAM, 0); if( DEBUGMOD&SCK && DEBUGMOD&HDR ) printf(" * [drop_udp_server] socket: %d\n", *pListenSock); /* 2. Gestion erreur */ if( *pListenSock < 0 ) return -1; /* [2] On définit les infos de la socket =========================================================*/ /* (1) Reset des valeurs */ bzero(pInfo, sizeof(struct sockaddr_in)); /* (2) On définit les infos */ pInfo->sin_family = AF_INET; pInfo->sin_port = htons(pPort); pInfo->sin_addr.s_addr = htonl(INADDR_ANY); /* [3] On publie la SOCKET =======================================================*/ /* 1. Publication socket */ int count = -1; do{ count++; pInfo->sin_port = htons(pPort+count); STATUS = bind(*pListenSock, (struct sockaddr*) pInfo, sizeof(struct sockaddr_in)); if( DEBUGMOD&SAD ) printf("\tudp:%d used, trying udp:%d\n", pPort+count-1, pPort+count); }while( STATUS < 0 && count < 10 ); if( DEBUGMOD&SCK && DEBUGMOD&HDR ) printf(" * [drop_udp_server] bind: %d\n", STATUS); /* 2. Gestion erreur */ if( STATUS < 0 ) return -1; /* 3. Demande groupe multicast (si demandé) */ if( pMcast ){ tmp.s_addr = pAddr; if( DEBUGMOD&SCK && DEBUGMOD&HDR ) printf(" * [drop_udp_server] join mcast group: %s\n", inet_ntoa(tmp)); mcastReq.imr_multiaddr.s_addr = pAddr; mcastReq.imr_interface.s_addr = htonl(INADDR_ANY); if( setsockopt(*pListenSock, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mcastReq, sizeof(mcastReq)) < 0 ){ close(*pListenSock); return -1; } } /* [n] Code succès =========================================================*/ return pPort+count; }