linux广播

linux广播


// 发送端
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
//#include <bits/socket.h>

//只有UDP套接字允许广播或多播,ipv4中的多播地址范围是:224.0.0.0到239.255.255.255

int main()
{
    setvbuf(stdout, NULL, _IONBF, 0);
    fflush(stdout);

    int sock = -1;
    if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
    {
        perror("socket error");
        return 0;
    }

    const int opt = 1;
    //设置该套接字为广播类型,
    int nb = 0;
    nb = setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (char *)&opt, sizeof(opt));
    if(nb == -1)
    {
        perror("set socket error...");
        return 0;
    }

    struct sockaddr_in addrto;
    bzero(&addrto, sizeof(struct sockaddr_in));
    addrto.sin_family=AF_INET;
    addrto.sin_addr.s_addr=htonl(INADDR_BROADCAST);
    addrto.sin_port=htons(6000);
    int nlen=sizeof(addrto);

    while(1)
    {
        sleep(1);
        //从广播地址发送消息
        char smsg[] = {"abcdef"};
        int ret=sendto(sock, smsg, strlen(smsg), 0, (struct sockaddr *)&addrto, nlen);
        if(ret<0)
        {
            perror("set socket error...");
        }
        else
        {
            printf("ok ");
        }
    }

    return 0;
}

 

 

// 接收端
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>

int main()
{
    setvbuf(stdout, NULL, _IONBF, 0);
    fflush(stdout);

    // 绑定地址
    struct sockaddr_in addrto;
    bzero(&addrto, sizeof(struct sockaddr_in));
    addrto.sin_family = AF_INET;
    addrto.sin_addr.s_addr = htonl(INADDR_ANY);
    addrto.sin_port = htons(6000);

    // 广播地址
    struct sockaddr_in from;
    bzero(&from, sizeof(struct sockaddr_in));
    from.sin_family = AF_INET;
    from.sin_addr.s_addr = htonl(INADDR_ANY);
    from.sin_port = htons(6000);

    int sock = -1;
    if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
    {
        perror("socket error\n");
        return 0;
    }

    const int opt = 1;//UDP默认不支持广播,设置该套接字为广播类型,opt = 1
    int nb = 0;
    nb = setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (char *)&opt, sizeof(opt));
    if(nb == -1)
    {
        perror("set socket error\n");
        return 0;
    }

    if(bind(sock,(struct sockaddr *)&(addrto), sizeof(struct sockaddr_in)) == -1)
    {
        perror("bind error\n");
        return 0;
    }

    int len = sizeof(struct sockaddr_in);
    char smsg[100] = {0};

    while(1)
    {
        //从广播地址接受消息
        int ret=recvfrom(sock, smsg, 100, 0, (struct sockaddr*)&from,(socklen_t*)&len);
        if(ret<=0)
        {
            perror("recvfrom error\n");
        }
        else
        {
            printf("%s\t", smsg);
        }

        sleep(1);
    }

    return 0;
}

 

posted @ 2019-07-25 21:27  PKICA  阅读(581)  评论(0编辑  收藏  举报