1 /* dgramrcv.c - receive from udp 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>
31 int main(int argc, char *argv[]) {
34 struct sockaddr_in local_addr,target_addr;
35 int receive_bytes, write_bytes;
36 socklen_t target_addr_len;
37 unsigned char buf[MAX_BUF];
40 printf("usage: %s <port>\n",argv[0]);
44 if((receive_fd=socket(AF_INET,SOCK_DGRAM,0)) == -1) {
45 printf("can't open socket.\n");
50 setsockopt(receive_fd,SOL_SOCKET,SO_BROADCAST,&opt,sizeof(opt));
52 local_addr.sin_family=AF_INET;
53 local_addr.sin_port=htons(atoi(argv[1]));
54 local_addr.sin_addr.s_addr=htonl(INADDR_ANY);
55 bind(receive_fd,(const struct sockaddr *)&local_addr,sizeof(local_addr));
57 memset(&target_addr,0,sizeof(target_addr));
59 target_addr.sin_family=AF_INET;
60 target_addr.sin_port=htons(atoi(argv[1]));
61 target_addr.sin_addr.s_addr=inet_addr(argv[1]);
62 target_addr_len=sizeof(target_addr);
66 while(receive_bytes>0) {
67 receive_bytes=recvfrom(receive_fd,buf,sizeof(buf),0,(struct sockaddr *)&target_addr,&target_addr_len);
68 write_bytes=write(1,buf,receive_bytes);
72 printf("connection closed ...\n");
73 printf("%d from %d total bytes written.\n",write_bytes,receive_bytes);