1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
| 1 #include<stdio.h>
2 #include<stdlib.h>
3 #include<errno.h>
4 #include<sys/types.h>
5 #include<sys/socket.h>
6 #include<unistd.h>
7 #include<string.h>
8 #include<arpa/inet.h>
9 #include<netinet/in.h>
10 void usage(char* argv)
11 {
12 printf("%s:[ip][port]\n",argv);
13 }
14
15 int main(int argc,char* argv[])
16 {
17 if(argc!=3) //判断传参错误
18 {
19 usage(argv[0]);
20 exit(1);
21 }
22 int port=atoi(argv[2]);
23 char* ip=argv[1];
24 //sock()
25 int sock=socket(AF_INET,SOCK_DGRAM,0); //创建套接字
26 if(sock<0)
27 {
28 perror("sock");
29 exit(2);
30 }
31 struct sockaddr_in local;
32 local.sin_family=AF_INET;
33 local.sin_port=htons(port);
34 local.sin_addr.s_addr=inet_addr(ip);
35 if(bind(sock,(struct sockaddr*)&local,sizeof(local))<0) //绑定本地地址
36 {
37 perror("bind\n"); //UDP面向无连接的,所以 无需进行监听,接收
38 exit(1);
39 }
40 struct sockaddr_in client;
41 socklen_t size=sizeof(client);
42 char buf[1024];
43 while(1)
44 {
45 size_t _s=recvfrom(sock,buf,sizeof(buf)-1,0,(struct sockaddr*)&clien t,&size);
46 if(_s>0)
47 {
48 buf[_s-1]='\0';
49 printf("[ip]:%s",inet_ntoa(client.sin_addr));
50 printf("[port]:%ld",ntohs(client.sin_port));
51 printf("get connection..\n");
52 printf("%s\n",buf);
53 }
54 else if(_s==0)
55 {
56 printf("client close\n");
57 }
58 else
59 {
60 perror("read");
61 }
62 }
63
64
65 return 0;
66 }
|