socket组播

socket组播socket组播

例:

发送组播报文代码如下:

mutilcast.c

#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <stdlib.h>

#define PORT 4000
#define MULTI_CAST_ADDR    "224.0.0.1"

int main(void)
{
    int sock_fd;
    struct sockaddr_in address;
    char buf[] = "test broadcast %-3dxxxxx";
    
    sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
    
    /* initialize the address struct */
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = inet_addr(MULTI_CAST_ADDR);
    address.sin_port = htons(PORT);
    
    /* start broadcasting */
    unsigned int count = 0;
    while(1) {
        sprintf(buf, "test broadcast %-5d", count);    
        //if( sendto(sock_fd, "test broadcast", sizeof("test broadcast"), 0, 
        if(sendto(sock_fd, buf, strlen(buf), 0, (struct sockaddr *)&address, sizeof(address))<0) {
            perror("sendto");
            exit( EXIT_FAILURE);
        }
        printf("Have send %d packets.\n", ++count);
        sleep(1);
    }
    return 0;    
}

接收报文代码:

recv.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <linux/in.h>
#include <unistd.h>
/*
 *receive data as "./recv port" 
 */

int    main(int argc, char *argv[])
{
    int sock_fd;
    struct sockaddr_in myaddr;
    struct sockaddr_in sendaddr;

    char buf[1024];
    int    recv_num;
    int    recvlen;
/*
    if(3 != argc)
    {
        printf("argc\n");
        exit(1);
    }
*/
    if(-1 == (sock_fd = socket(PF_INET, SOCK_DGRAM, 0)))
    {
        printf("socket\n");
        exit(2);
    }

    myaddr.sin_family = AF_INET;
    myaddr.sin_port = htons(atoi(argv[1]));
    myaddr.sin_addr.s_addr = htonl(INADDR_ANY);

    if(-1 == bind(sock_fd, (struct sockaddr *)&myaddr, sizeof(struct sockaddr_in)))
    {
        perror("bind");
        exit(1);
    }
    memset(buf, 0, 1024);
    recvlen = sizeof(struct sockaddr_in);
    while(1) {
        recv_num = recvfrom(sock_fd, (char *)buf, sizeof(buf), 0, 
                    (struct sockaddr *)&sendaddr, &recvlen);  
        printf("%s\n", buf);
    }
/*
    to.sin_family = AF_INET;
    to.sin_port = htons(atoi(argv[2]));
    to.sin_addr.s_addr = inet_addr(argv[1]);
    
    int ret = sendto(sock_fd, buf, strlen(buf) + 1, 0,
                (struct sockaddr *)&to, sizeof(struct sockaddr_in));
    if(-1 == ret)
    {
        printf("sendto");
        exit(2);
    }
*/
    close(sock_fd);
}

编译链接后, 分别在两个PC终端运行,输出如下:

 

posted @ 2016-01-25 10:34  zhanglong71  阅读(1145)  评论(0编辑  收藏  举报