-
[my-code/ivac.git] / datagram.c
1 /* datagram.c - datagram sockets 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 /* open */
30 #include <sys/stat.h>
31 #include <fcntl.h>
32
33 int main(int argc, char *argv[]) {
34   int send_fd,broadcast_on;
35   struct sockaddr_in local_addr, remote_addr;
36   socklen_t remote_addr_len,optlen;
37   int send_bytes, read_bytes;
38   FILE *cmd_fd;
39
40   if(argc!=4) {
41     printf("usage: %s \"cmd command\" <target-ip/broadcast-addr> <port>\n",argv[0]);
42     exit(1);
43   }
44
45   if((send_fd=socket(AF_INET,SOCK_DGRAM,0)) == -1) {
46     printf("can't open socket.\n");
47     exit(1);
48   }
49
50   broadcast_on=1;
51   optlen=sizeof(broadcast_on);
52   if((setsockopt(send_fd,SOL_SOCKET,SO_BROADCAST,&broadcast_on,optlen))==-1)
53     perror("setsockopt");
54   
55  
56   memset(&local_addr,0,sizeof(local_addr));
57   local_addr.sin_family=AF_INET;
58   local_addr.sin_port=htons(atoi(argv[3]));
59   local_addr.sin_addr.s_addr=htonl(INADDR_ANY);
60
61   if(bind(send_fd,(struct sockaddr *)&local_addr,sizeof(local_addr))==-1) {
62     printf("unable to bind on port %d.\n",atoi(argv[3]));
63     perror("bind");
64     exit(1);
65   }
66
67   remote_addr_len=sizeof(remote_addr); 
68   memset(&remote_addr,0,sizeof(remote_addr));
69   remote_addr.sin_family=AF_INET;
70   remote_addr.sin_port=htons(atoi(argv[3]));
71   remote_addr.sin_addr.s_addr=inet_addr(argv[2]);
72
73   if((cmd_fd=popen(argv[1],"w"))<0) {
74     printf("unable to open file descriptor for %s.\n",argv[1]);
75     exit(1);
76   }
77
78   /* send stuff .... */
79   read_bytes=1;
80   while(read_bytes>0) {
81     unsigned char buf[1000];
82     read_bytes=read(0,buf,sizeof(buf));
83     send_bytes=sendto(send_fd,buf,read_bytes,0,(struct sockaddr *)&remote_addr,remote_addr_len);
84 #ifdef DEBUG
85     perror("sendto");
86 #endif
87      
88     fwrite(buf,read_bytes,1,cmd_fd);
89   }
90
91   close(send_fd);
92   printf("connection closed ...\n");
93   printf("%d from %d total bytes sent.\n",send_bytes,read_bytes);
94
95   return 0;
96 }