码迷,mamicode.com
首页 > 其他好文 > 详细

UDP编程之二

时间:2014-06-18 15:55:32      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   color   os   

广播模型

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>\n",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\n",buf);
    }

    close(sockfd);
    return 0;
}

 

UDP编程之二,布布扣,bubuko.com

UDP编程之二

标签:style   class   blog   code   color   os   

原文地址:http://www.cnblogs.com/xiaoying1245970347/p/3791141.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!