--
[my-code/ivac.git] / datagram.c
index a140c32..bcee943 100644 (file)
 /* read, close */
 #include <unistd.h>
 
+/* open */
+#include <sys/stat.h>
+#include <fcntl.h>
+
 int main(int argc, char *argv[]) {
-  int send_fd;
+  int send_fd,broadcast_on;
   struct sockaddr_in local_addr, remote_addr;
-  socklen_t remote_addr_len;
-  int send_bytes;
+  socklen_t remote_addr_len,optlen;
+  int send_bytes, read_bytes;
+  FILE *cmd_fd;
 
-  if(argc!=3) {
-    printf("usage: %s <target-ip/broadcast-addr> <port>\n",argv[0]);
+  if(argc!=4) {
+    printf("usage: %s \"cmd command\" <target-ip/broadcast-addr> <port>\n",argv[0]);
     exit(1);
   }
 
@@ -41,30 +46,46 @@ int main(int argc, char *argv[]) {
     printf("can't open socket.\n");
     exit(1);
   }
+
+  broadcast_on=1;
+  optlen=sizeof(broadcast_on);
+  if((setsockopt(send_fd,SOL_SOCKET,SO_BROADCAST,&broadcast_on,optlen))==-1)
+    perror("setsockopt");
+  
  
   memset(&local_addr,0,sizeof(local_addr));
   local_addr.sin_family=AF_INET;
-  local_addr.sin_port=htons(atoi(argv[2]));
+  local_addr.sin_port=htons(atoi(argv[3]));
   local_addr.sin_addr.s_addr=htonl(INADDR_ANY);
 
   if(bind(send_fd,(struct sockaddr *)&local_addr,sizeof(local_addr))==-1) {
-    printf("unable to bind on port %d.\n",atoi(argv[1]));
+    printf("unable to bind on port %d.\n",atoi(argv[3]));
     perror("bind");
     exit(1);
   }
 
-  // remote_addr_len=sizeof(remote_addr); 
+  remote_addr_len=sizeof(remote_addr); 
   memset(&remote_addr,0,sizeof(remote_addr));
   remote_addr.sin_family=AF_INET;
-  remote_addr.sin_port=htons(atoi(argv[2]));
-  remote_addr.sin_addr=inet_addr(argv[1]);
+  remote_addr.sin_port=htons(atoi(argv[3]));
+  remote_addr.sin_addr.s_addr=inet_addr(argv[2]);
+
+  if((cmd_fd=popen(argv[1],"w"))<0) {
+    printf("unable to open file descriptor for %s.\n",argv[1]);
+    exit(1);
+  }
 
   /* send stuff .... */
   read_bytes=1;
   while(read_bytes>0) {
     unsigned char buf[1000];
     read_bytes=read(0,buf,sizeof(buf));
-    send_bytes=sendto(send_fd,buf,sizeof(buf),&remote_addr,sizeof(remote_addr);
+    send_bytes=sendto(send_fd,buf,read_bytes,0,(struct sockaddr *)&remote_addr,remote_addr_len);
+#ifdef DEBUG
+    perror("sendto");
+#endif
+     
+    fwrite(buf,read_bytes,1,cmd_fd);
   }
 
   close(send_fd);