广播

广播:(UDP)

  发送方发送的广播数据包会传送到该局域网中的所有主机中,主机上的接收方可以接收到该数据包

255.255.255.255和192.168.4.255,都可以给本网段广播;

步骤:

  发送:socket—>setsockopt(允许广播发送)-->sendto(广播地址)

  接收:socket—>bind—>recvfrom

案例:

广播:

#include<stdio.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <string.h>
#include <unistd.h>

#include <arpa/inet.h>





int main(void)
{
    int skt = socket(AF_INET, SOCK_DGRAM, 0);
    
    if(-1 == skt)
    {
        printf("socker error\n");
        return -1;
    }
    
    //设置为可广播模式
    int on = 1;
    setsockopt(skt, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on));
    
    //将IP和端口号存入结构体
    struct sockaddr_in sddr;
    sddr.sin_family     = AF_INET;
    sddr.sin_port       = htons(7777);
    sddr.sin_addr.s_addr    = inet_addr("192.168.4.255");
    int len = sizeof(struct sockaddr_in);

    char buf[100] = {'\0'};
    while(1)
    {
        fgets(buf,100,stdin);
        sendto(skt, buf, sizeof(buf), 0, (struct sockaddr *)&sddr, len);
        puts(buf);
        memset(buf, 0,sizeof(buf));
    }
    close(skt);
    return 0;
}

广播接收:

#include<stdio.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <string.h>
#include <unistd.h>

#include <arpa/inet.h>

int main(void)
{
    int skt = socket(AF_INET, SOCK_DGRAM, 0);
    
    if(-1 == skt)
    {
        printf("socker error\n");
        return -1;
    }
    //将IP和端口号存入结构体
    struct sockaddr_in sddr;
    sddr.sin_family     = AF_INET;
    sddr.sin_port       = htons(7777);
    sddr.sin_addr.s_addr    = inet_addr("0.0.0.0");
    int len = sizeof(struct sockaddr_in);
    //将套接字和IP、端口号进行绑定
    int ret = bind(skt, (struct sockaddr *)&sddr, sizeof(sddr));
    if(-1 == ret)
    {
        printf("bind error\n");
        return -1;
    }
    char buf[100] = {'\0'};
    while(1)
    {
        recvfrom(skt, buf, sizeof(buf), 0, (struct sockaddr *)&sddr, &len);//0表示阻塞
        puts(buf);
    }
    close(skt);
    return 0;
}

 

posted @ 2022-04-08 13:26  西北小蚂蚁  阅读(99)  评论(0编辑  收藏  举报