Linux C/C++广播

发布时间 2023-10-26 11:45:55作者: 阿风小子

一、流程实现


二、代码实现
1.服务器
代码如下(示例):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

int main()
{
    // 1.创建一个通信的socket
    int fd = socket(PF_INET, SOCK_DGRAM, 0);

    if (fd == -1)
    {
        perror("socket");
        exit(-1);
    }

    // 2.设置广播属性
    int op = 1;
    setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &op, sizeof(op));

    //3.创建一个广播的地址
    struct sockaddr_in caddr;
    caddr.sin_family = AF_INET;
    caddr.sin_port = htons(9999);
    inet_pton(AF_INET,"192.168.15.255",&caddr.sin_addr.s_addr);

    // 4.通信
    int num = 0;
    while (1)
    {
        char sendbuf[128];
        sprintf(sendbuf, "hello,client.....%d\n", num++);
        //发送数据
        sendto(fd, sendbuf, strlen(sendbuf) + 1,0,(struct sockaddr*)&caddr,sizeof(caddr));
        printf("广播的数据:%s\n", sendbuf);
        sleep(1);
    }

    close(fd);

    return 0;
}


2.客户端
代码如下(示例):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

int main()
{
    // 1.创建一个通信的socket
    int fd = socket(PF_INET, SOCK_DGRAM, 0);

    if (fd == -1)
    {
        perror("socket");
        exit(-1);
    }

    //2.客户端绑定本地的IP和端口号
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(9999);
    addr.sin_addr.s_addr = INADDR_ANY;

    int ret = bind(fd, (struct sockaddr *)&addr, sizeof(addr));
    if(ret ==-1 )
    {
        perror("bind");
        exit(-1);
    }

    // 3.通信
    while (1)
    {
        char buf[128];
        //接受数据
        int num = recvfrom(fd, buf, sizeof(buf), 0, NULL, NULL);
        printf("server say:%s\n", buf);

    }

    close(fd);

    return 0;
}