/* receiver for internet datagram demo */ /* modification 9/20/93 with Louis Sanchez's bug fix */ #include #include #include #include #include #include #define ENDPACKET "end" /************************************************************ printsockaddr prints the contents of a sockaddr_in structure when called with a pointer to such a structure. ************************************************************/ void printsockaddr(struct sockaddr_in *arg) { struct hostent *hp; printf(" sockaddr_in: "); printf("Domain=%d, ", arg->sin_family); hp=gethostbyaddr((const char *)&(arg->sin_addr), sizeof(arg->sin_addr), AF_INET); printf("Hostname=%s, ", hp->h_name); printf("Port=%d, ", ntohs(arg->sin_port)); printf("Address=%s,\n", inet_ntoa(arg->sin_addr)); } help_msg() { printf("format: idgr -[d]\n"); printf(" option: d set debug mode\n"); } main(argc, argv) int argc; char *argv[]; { int sock; struct sockaddr_in from; int n, i; char toBuf[2048]; char fromBuf[2048]; int length; int flag = 1; extern char *optarg; extern int optind; int option_exist = 0; int debug = 0; int c; FILE *fp; /* process command line args */ while ((c=getopt(argc,argv,"d")) != EOF) { option_exist = 1; switch(c) { case 'd': debug = 1; if (debug) printf("turn on debug mode.\n"); break; case '?': help_msg(); exit (1); default: fprintf (stderr, "unrecognized arg >%s<\n", optarg); help_msg(); exit (1); } } /* create socket */ sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock < 0) { perror("opening datagram socket"); exit(1); } /* create name structure with wildcard using INADDR_ANY */ from.sin_family = AF_INET; from.sin_addr.s_addr = INADDR_ANY; from.sin_port = htons(8345); /* port no. < 1024 IPPORT_RESERVED is for privillege process */ /* here just initialized it, it will be assigned value after call */ /* getsockname() */ if (bind(sock, &from, sizeof(struct sockaddr_in))) { perror("binding name to datagram socket"); exit(1); } length = sizeof(from); if (getsockname(sock, &from, &length)) { perror("getting socket name"); exit(1); } /* Find assigned port value and print out. */ printf("socket has port #%d\n", ntohs(from.sin_port)); fprintf(stderr, "socket has port #%d\n", ntohs(from.sin_port)); fp = fopen("idgrrp_port", "w"); fprintf(fp, "idgrrp port=%d\n", ntohs(from.sin_port)); fclose(fp); /* receive message */ while (flag) { n = recvfrom(sock, fromBuf, sizeof(fromBuf), 0, &from, &length); if (n < 0) perror("receiving datagram message"); fromBuf[n] = 0; /* null terminate */ if (debug) { printf("The no. of bytes received=%d\n", n); printf("received msg="); for (i=0; i