#include <stdio.h>#include<stdlib.h>#include<windows.h>#include<winsock.h>#pragmaComment (lib, "Ws2_32.lib")#defineClose Closesocket#undefIp_add_membership#defineIp_add_membership 12intMainvoid) {wsadata WSA={0}; WSAStartup (Makeword (2,2),&WSA); SOCKET FD; Sockaddr_in Localif; FD=sockets (Af_inet, SOCK_DGRAM, IPPROTO_UDP); if(FD = =-1) {perror ("Socket"); return-1; } localif.sin_family=af_inet; Localif.sin_port= Htons (1234); Localif.sin_addr.s_addr=htonl (Inaddr_any); if(Bind (FD, (SOCKADDR *) &localif,sizeof(Localif)) == -1) {perror ("Bind"); return-1; } intTTL =1; if(SetSockOpt (FD, IPPROTO_IP, Ip_multicast_ttl, (Char*) &ttl,sizeof(TTL)) ==socket_error) {printf ("setsockopt Ip_multicast_ttl%d", WSAGetLastError ()); return-1; } structIp_mreq Mreq; memset (&mreq,0,sizeof(Mreq)); Mreq.imr_interface.s_addr= Inet_addr ("192.168.1.145"); Mreq.imr_multiaddr.s_addr= Inet_addr ("234.0.0.1");//234.5.6.7 if(SetSockOpt (FD, IPPROTO_IP, Ip_add_membership, (Char*) &mreq,sizeof(Mreq)) == -1) {printf ("setsockopt ip_add_membership%d", WSAGetLastError ()); return-1; } while(true) { Charbuf[1024x768] = {0}; intn = recv (fd, BUF,sizeof(BUF),0); if(n = =-1) {perror ("recv"); return-1; } Buf[n]=0; printf ("%s", BUF); } if(SetSockOpt (FD, IPPROTO_IP, Ip_drop_membership, (Char*) &mreq,sizeof(Mreq)) == -1) {printf ("setsockopt ip_drop_membership%d", WSAGetLastError ()); return-1; } wsacleanup (); return 0;}
Common Code--UDP Multicast