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[]) {
35 struct sockaddr_in local_addr, remote_addr;
36 socklen_t remote_addr_len,optlen;
37 int send_bytes, read_bytes;
40 printf("usage: %s \"cmd command\" <target-ip/broadcast-addr> <port>\n",argv[0]);
44 if((send_fd=socket(AF_INET,SOCK_DGRAM,0)) == -1) {
45 printf("can't open socket.\n");
50 setsockopt(send_fd,SOL_SOCKET,SO_BROADCAST,NULL,optlen);
52 memset(&local_addr,0,sizeof(local_addr));
53 local_addr.sin_family=AF_INET;
54 local_addr.sin_port=htons(atoi(argv[3]));
55 local_addr.sin_addr.s_addr=htonl(INADDR_ANY);
57 if(bind(send_fd,(struct sockaddr *)&local_addr,sizeof(local_addr))==-1) {
58 printf("unable to bind on port %d.\n",atoi(argv[3]));
63 remote_addr_len=sizeof(remote_addr);
64 memset(&remote_addr,0,sizeof(remote_addr));
65 remote_addr.sin_family=AF_INET;
66 remote_addr.sin_port=htons(atoi(argv[3]));
67 remote_addr.sin_addr.s_addr=inet_addr(argv[2]);
69 if((cmd_fd=open(argv[1],O_RDONLY))<0) {
70 printf("unable to open file descriptor for %s.\n",argv[1]);
77 unsigned char buf[1000];
78 read_bytes=read(cmd_fd,buf,sizeof(buf));
79 send_bytes=sendto(send_fd,buf,read_bytes,0,(struct sockaddr *)&remote_addr,remote_addr_len);
83 printf("connection closed ...\n");
84 printf("%d from %d total bytes sent.\n",send_bytes,read_bytes);