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>
29 int main(int argc, char *argv[]) {
32 struct sockaddr_in local_addr,target_addr;
33 int receive_bytes, write_bytes;
34 socklen_t target_addr_len;
37 printf("usage: %s <port>\n",argv[0]);
41 if((receive_fd=socket(AF_INET,SOCK_DGRAM,0)) == -1) {
42 printf("can't open socket.\n");
47 setsockopt(receive_fd,SOL_SOCKET,SO_BROADCAST,&opt,sizeof(opt));
49 local_addr.sin_family=AF_INET;
50 local_addr.sin_port=htons(atoi(argv[1]));
51 local_addr.sin_addr.s_addr=htonl(INADDR_ANY);
52 bind(receive_fd,(const struct sockaddr *)&local_addr,sizeof(local_addr));
54 memset(&target_addr,0,sizeof(target_addr));
55 target_addr.sin_family=AF_INET;
56 target_addr.sin_port=htons(atoi(argv[1]));
57 target_addr.sin_addr.s_addr=inet_addr(argv[1]);
58 target_addr_len=sizeof(target_addr);
61 while(receive_bytes>0) {
62 unsigned char buf[1000];
63 receive_bytes=recvfrom(receive_fd,buf,sizeof(buf),0,(struct sockaddr *)&target_addr,&target_addr_len);
64 write_bytes=write(1,buf,receive_bytes);
68 printf("connection closed ...\n");
69 printf("%d from %d total bytes written.\n",write_bytes,receive_bytes);