#include <winsock2.h> #include <stdio.h> #define MCASTADDR "234.5.6.101" //本例使用的多播组地址。 #define MCASTPORT 7000 //绑定的本地端口号。 #define BUFSIZE 5000 //接收数据缓冲大小。 int main( int argc,char ** argv) { WSADATA wsd; struct sockaddr_in local; //本地 struct sockaddr_in remote; //组播源 struct sockaddr_in from;; //实际数据来源 SOCKET sock; SOCKET sockM; char recvbuf[BUFSIZE]; int len = sizeof(struct sockaddr_in); int ret; //初始化WinSock2.2 if(WSAStartup(MAKEWORD(2,2),&wsd) != 0 ) { printf("WSAStartup() failed\n"); return -1; } if((sock = WSASocket(AF_INET, SOCK_DGRAM, 0, NULL, 0, WSA_FLAG_MULTIPOINT_C_LEAF | WSA_FLAG_MULTIPOINT_D_LEAF | WSA_FLAG_OVERLAPPED)) == INVALID_SOCKET) { printf("socket failed with:%d\n",WSAGetLastError()); WSACleanup(); return -1; } //将sock绑定到本机某端口上。 local.sin_family = AF_INET; local.sin_port = htons(MCASTPORT); local.sin_addr.s_addr = INADDR_ANY; if(bind(sock, (struct sockaddr*)&local, sizeof(local)) == SOCKET_ERROR ) { printf( "bind failed with:%d \n",WSAGetLastError()); closesocket(sock); WSACleanup(); return -1; } //加入多播组 remote.sin_family = AF_INET; remote.sin_port = htons(MCASTPORT); remote.sin_addr.s_addr = inet_addr(MCASTADDR ); if((sockM = WSAJoinLeaf(sock,(SOCKADDR*)&remote,sizeof(remote),NULL,NULL,NULL,NULL, JL_BOTH)) == INVALID_SOCKET) { printf("WSAJoinLeaf() failed:%d\n",WSAGetLastError()); closesocket(sock); WSACleanup(); return -1; } FILE * pFile; if ((pFile = fopen(".\\out.264", "wb")) == NULL) { printf("Cannot open file!\n"); } bool bIsStart = false; while(1) { ret = recvfrom(sock,recvbuf,BUFSIZE,0,(struct sockaddr*)&from, &len); // ret = recvfrom(sock, recvbuf, BUFSIZE, 0, NULL, NULL); if(ret == SOCKET_ERROR) { printf("recvfrom failed with:%d\n", WSAGetLastError()); closesocket(sockM); closesocket(sock); WSACleanup(); return -1; } if (bIsStart == false) { if ((recvbuf[26] == 0x00) && (recvbuf[27] == 0x01) && (recvbuf[28] == 0x67)) { bIsStart = true; } else { continue; } } fwrite(recvbuf + 24, sizeof(char), ret - 24, pFile); } closesocket(sockM); closesocket(sock); WSACleanup(); return 0; }
注意:附加依赖项中要添加ws2_32.lib