linux下基于UDP的广播通信

2022-08-18


场景

存在两个角色,一个是“发布者”,另一个是“订阅者”。双方均处于同一局域网。发布者定时向局域网内所有主机发布消息,订阅者负责接收这一消息。

 

实现

在linux环境下,使用C语言基于UDP的广播来实现是最便捷的。并且在同一局域网内几乎不用担心UDP的通信可靠性问题。

 

发布者示例程序

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

int main()
{
    printf("hello world\n");
    struct sockaddr_in sin;
    int sfd;

    sfd = socket(AF_INET, SOCK_DGRAM, 0);
    printf("UDP socket fd:%d\n", sfd);

    int sb = 1;
    int ret = setsockopt(sfd, SOL_SOCKET, SO_BROADCAST, &sb, sizeof(int)); //打开广播通信的权限
    printf("set sock opt ret:%d\n", ret);

    memset(&sin, 0, sizeof(struct sockaddr_in));
    sin.sin_family = AF_INET;
    sin.sin_port = htons(8611); //通信端口号。发布者与订阅者必须一致。
    sin.sin_addr.s_addr = htonl(INADDR_BROADCAST);
    printf("config IP-address success\n");

    char* words = "hi there\n";
    int slen;
    while(1)
    {
        slen = sendto(sfd, words, strlen(words), 0, (struct sockaddr*)&sin, sizeof(sin));
        printf("%s sent %d\n", words, slen);
        sleep(3);
    }

    return 0;
}

 

 

订阅者示例程序

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

int main()
{
    struct sockaddr_in sin;
    int sfd;
    int ret;

    sfd = socket(AF_INET, SOCK_DGRAM, 0);
    printf("socket fd:%d\n", sfd);

    int sb = 1;
    ret = setsockopt(sfd, SOL_SOCKET, SO_BROADCAST, &sb, sizeof(int)); //The permission
    printf("set sock opt ret:%d\n", ret);

    sin.sin_addr.s_addr = htonl(INADDR_BROADCAST); //255.255.255.255
    sin.sin_family = AF_INET;
    sin.sin_port = htons(8611); //Very important

    ret = bind(sfd, (struct sockaddr*)&sin, sizeof(sin));
    printf("bind ret:%d\n", ret);

    char rbuf[256];
    int rlen;
    while(1)
    {
            rlen = recvfrom(sfd, rbuf, 255, 0, NULL, NULL);
            rbuf[rlen] = 0;
            printf("rlen:%d, %s\n", rlen, rbuf);
    }

    return 0;
}

 


 

posted @ 2022-08-18 17:07  大窟窿  阅读(676)  评论(0编辑  收藏  举报