c/c++常用代码--udp多播

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <winsock.h>

#pragma comment(lib, "ws2_32.lib")

#define close closesocket

#undef IP_ADD_MEMBERSHIP
#define IP_ADD_MEMBERSHIP 12


int main(void)
{    
    WSADATA wsa={0};
    WSAStartup(MAKEWORD(2,2),&wsa);


    SOCKET fd;
    SOCKADDR_IN localif;    

    fd = socket(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;    
    }


    int ttl = 1;
    if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_TTL, (char *)&ttl, sizeof(ttl)) == SOCKET_ERROR) {
        printf("setsockopt IP_MULTICAST_TTL %d", WSAGetLastError());        
        return -1;    
    }


    struct ip_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) {
        char buf[1024] = {0};
        int n = 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;
}

 

posted @ 2015-01-09 22:46  崇山峻岭  阅读(517)  评论(0编辑  收藏  举报