UDP编程之一

单播模型

echoserver.c

 

 1 #include <apue.h>
 2 
 3 #define PORT 8080
 4 #define LEN_BUF 255
 5 
 6 void do_business(int sockfd);
 7 
 8 int main(void)
 9 {
10     //1.创建socket
11     int sockfd;
12     if((sockfd = socket(PF_INET,SOCK_DGRAM,0))<0)
13         ERR("socket failed");
14 
15     //2.绑定地址
16     struct sockaddr_in ipv4;
17     CLEAR(ipv4);
18     ipv4.sin_family = AF_INET;
19     ipv4.sin_port = htons(PORT);                    //NBO
20     //inet_pton(AF_INET,IP,&ipv4.sin_addr);
21     ipv4.sin_addr.s_addr = htonl(INADDR_ANY);        //NBO
22 
23     if(bind(sockfd,(struct sockaddr*)&ipv4,sizeof(ipv4))<0)    
24         ERR("bind failed");
25 
26     //3.交互
27     do_business(sockfd);
28 
29     //4.关闭
30     close(sockfd);
31     return 0;
32 }
33 
34 void do_business(int sockfd)
35 {
36     struct sockaddr_in peer;
37     char buf[LEN_BUF];
38     socklen_t len = sizeof(peer);
39     int n;
40     while(1)
41     {
42         if((n = recvfrom(sockfd,buf,sizeof(buf),0,(struct sockaddr*)&peer,&len))<0)
43             ERR("recv failed");
44         if(sendto(sockfd,buf,n,0,(struct sockaddr*)&peer,sizeof(peer))<0)
45             ERR("send failed");
46     }
47 }

echoclient.c

 1 #include <apue.h>
 2 
 3 #define PORT 8080
 4 #define LEN_BUF 255
 5 
 6 void do_business(const char *ipstr,unsigned short port,int sockfd);
 7 
 8 int main(int argc,char **argv)
 9 {
10     //0.解析命令行参数
11     if(argc!=3)
12     {
13         printf("Usage: %s <ip> <port>\n",argv[0]);
14         exit(0);
15     }
16     unsigned short port = strtol(argv[2],NULL,10);
17 
18     //1.创建socket
19     int sockfd;
20     if((sockfd = socket(PF_INET,SOCK_DGRAM,0))<0)
21         ERR("socket failed");
22 
23     //3.交互
24     do_business(argv[1],port,sockfd);
25 
26     //4.关闭
27     close(sockfd);
28     return 0;
29 }
30 
31 void do_business(const char *ipstr,unsigned short port,int sockfd)
32 {
33     struct sockaddr_in peer;
34     CLEAR(peer);
35     peer.sin_family = AF_INET;
36     peer.sin_port = htons(port);
37     inet_pton(AF_INET,ipstr,&peer.sin_addr);
38 
39     char buf[LEN_BUF],msg[LEN_BUF];
40     int n;
41     while(1)
42     {
43         printf("shell# ");
44         fflush(stdout);
45         scanf("%s",buf);
46         if(sendto(sockfd,buf,strlen(buf),0,(struct sockaddr*)&peer,sizeof(peer))<0)
47             ERR("send failed");
48         if((n = recvfrom(sockfd,msg,LEN_BUF,0,NULL,NULL))<0)
49             ERR("recv failed");
50         msg[n] = 0;
51         printf("%s\n",msg);
52     }
53 }

 

posted @ 2014-06-16 15:59  尾巴草  阅读(145)  评论(0编辑  收藏  举报