1 /* datagram.c - datagram sockets server
13 /* socket and bind stuff */
14 #include <sys/types.h>
15 #include <sys/socket.h>
18 #include <netinet/in.h>
21 #include <arpa/inet.h>
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;
41 printf("usage: %s \"cmd command\" <target-ip/broadcast-addr> <port>\n",argv[0]);
45 if((send_fd=socket(AF_INET,SOCK_DGRAM,0)) == -1) {
46 printf("can't open socket.\n");
51 optlen=sizeof(broadcast_on);
52 if((setsockopt(send_fd,SOL_SOCKET,SO_BROADCAST,&broadcast_on,optlen))==-1)
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);
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]));
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]);
73 if((cmd_fd=popen(argv[1],"w"))<0) {
74 printf("unable to open file descriptor for %s.\n",argv[1]);
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);
88 fwrite(buf,read_bytes,1,cmd_fd);
92 printf("connection closed ...\n");
93 printf("%d from %d total bytes sent.\n",send_bytes,read_bytes);