]> www.hackdaworld.org Git - my-code/ivac.git/blob - dgramrcv.c
d235b660f590ea1e602f23bd4efc32854666d393
[my-code/ivac.git] / dgramrcv.c
1 /* dgramrcv.c - receive from udp server
2  *
3  * author: hackbard
4  *
5  */
6
7 #include <stdio.h>
8 #include <stdlib.h>
9
10 /* memset */
11 #include <string.h>
12
13 /* socket and bind stuff */
14 #include <sys/types.h>
15 #include <sys/socket.h>
16
17 /* sockkaddr_in */
18 #include <netinet/in.h>
19
20 /* inet_ntoa ... */
21 #include <arpa/inet.h>
22
23 /* errno stuff ... */
24 #include <errno.h>
25
26 /* read, close */
27 #include <unistd.h>
28
29 int main(int argc, char *argv[]) {
30   int receive_fd;
31   int opt;
32   struct sockaddr_in local_addr,target_addr;
33   int receive_bytes, write_bytes;
34   socklen_t target_addr_len;
35
36   if(argc!=2) {
37     printf("usage: %s <port>\n",argv[0]);
38     exit(1);
39   }
40
41   if((receive_fd=socket(AF_INET,SOCK_DGRAM,0)) == -1) {
42     printf("can't open socket.\n");
43     exit(1);
44   }
45
46   opt=1;
47   setsockopt(receive_fd,SOL_SOCKET,SO_BROADCAST,&opt,sizeof(opt));
48
49   local_addr.sin_family=AF_INET;
50   local_addr.sin_port=htons(atoi(argv[1]));
51   local_addr.sin_addr.s_addr=htonl(INADDR_ANY);
52   bind(receive_fd,(const struct sockaddr *)&local_addr,sizeof(local_addr));
53  
54   memset(&target_addr,0,sizeof(target_addr));
55   target_addr.sin_family=AF_INET;
56   target_addr.sin_port=htons(atoi(argv[1]));
57   target_addr.sin_addr.s_addr=inet_addr(argv[1]);
58   target_addr_len=sizeof(target_addr);
59
60   receive_bytes=1;
61   while(receive_bytes>0) {
62         unsigned char buf[1000];
63         receive_bytes=recvfrom(receive_fd,buf,sizeof(buf),0,(struct sockaddr *)&target_addr,&target_addr_len);
64         write_bytes=write(1,buf,receive_bytes);
65   }
66
67   close(receive_fd);
68   printf("connection closed ...\n");
69   printf("%d from %d total bytes written.\n",write_bytes,receive_bytes);
70   
71   return 0;
72 }