Linux C/C++广播

35 篇文章 0 订阅
35 篇文章 0 订阅


一、流程实现

在这里插入图片描述

二、代码实现

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值