码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-01-09 23:31:54      阅读:282      评论:0      收藏:0      [点我收藏+]

标签:

#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;
}

 

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

标签:

原文地址:http://www.cnblogs.com/wansui/p/4214263.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!