• UDP编程之二


    广播模型

    broadcast.c

     1 #include <apue.h>
     2 
     3 #define PORT 8088
     4 
     5 int main(int argc,char **argv)
     6 {
     7     if(argc!=2)
     8     {
     9         printf("%s <msg>
    ",argv[0]);
    10         exit(0);
    11     }
    12 
    13     int sockfd;
    14     if((sockfd = socket(AF_INET,SOCK_DGRAM,0))<0)
    15         ERR("socket failed");
    16     
    17     //设置允许广播
    18     int val = 1;
    19     if(setsockopt(sockfd,SOL_SOCKET,SO_BROADCAST,&val,sizeof(val))<0)
    20         ERR("setsockopt failed");
    21 
    22     struct sockaddr_in peer;
    23     CLEAR(peer);
    24     peer.sin_family = AF_INET;
    25     peer.sin_port = htons(PORT);
    26     inet_pton(AF_INET,"192.168.5.255",&peer.sin_addr);
    27 
    28     if(sendto(sockfd,argv[1],strlen(argv[1]),0,(struct sockaddr*)&peer,sizeof(peer))<0)
    29         ERR("send failed");
    30     
    31     close(sockfd);
    32     return 0;
    33 }

    recv.c

    #include <apue.h>
    
    #define PORT 8088
    
    int main(int argc,char **argv)
    {
        int sockfd;
        if((sockfd = socket(AF_INET,SOCK_DGRAM,0))<0)
            ERR("socket failed");
        
        struct sockaddr_in ipv4;
        CLEAR(ipv4);
        ipv4.sin_family = AF_INET;
        ipv4.sin_port = htons(PORT);
        ipv4.sin_addr.s_addr = htonl(INADDR_ANY);
        if(bind(sockfd,(struct sockaddr*)&ipv4,sizeof(ipv4))<0)
            ERR("bind failed");
    
        int n;
        char buf[255];
        while(1)
        {
            if((n = recvfrom(sockfd,buf,sizeof(buf),0,NULL,NULL))<0)
                ERR("recv failed");
            buf[n] = 0;
            printf("%s
    ",buf);
        }
    
        close(sockfd);
        return 0;
    }
  • 相关阅读:
    设计模式之策略设计模式
    我的Java编码规范
    Jvm中的垃圾回收
    Jvm运行时内存解析
    SSH框架的搭建
    xshell5运行hadoop集群
    安装虚拟机和网络配置
    大数据技术原理与运用知识
    Redis高级应用解析:缓存穿透、击穿、雪崩
    B+Tree原理及mysql的索引分析
  • 原文地址:https://www.cnblogs.com/xiaoying1245970347/p/3791141.html
Copyright © 2020-2023  润新知