/* receiver for internet datagram demo */ #include #include #include #include #define ENDPACKET "end" help_msg() { printf("format: idgr\n"); } main(argc, argv) int argc; char *argv[]; { int sockTo; int sockFrom; struct sockaddr_in to; struct sockaddr_in from; struct hostent *hp, *gethostbyname(); int n, i; char c; char toBuf[1024]; char fromBuf[1024]; char hostname[64]; extern char *optarg; extern int optind; int option_exist = 0; int c; int debug = 0; char rcv_name[64]; /* receiver's socket name */ int toPort_no; int length; int fromlen; int quitFlag = 1; /* create socket from which to read */ sockFrom = socket(AF_INET, SOCK_DGRAM, 0); if (sockFrom < 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 = 0; /* port no. < 1024 IPPORT_RESERVED is for privillege process */ /* here just initialized it, it will be assigned value after call */ /* getsockname() */ if (bind(sockFrom, &from, sizeof(struct sockaddr_in))) { perror("binding name to datagram socket"); exit(1); } length = sizeof(from); if (getsockname(sockFrom, &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)); /* create socket on which to sent */ sockTo = socket(AF_INET, SOCK_DGRAM, 0); if (sockTo < 0) { perror("opening datagram socket"); exit(1); } to.sin_family = AF_INET; to.sin_addr.s_addr = INADDR_ANY; to.sin_port = 0; /* without this line, SUN version was denied in bind() */ if (bind(sockTo, &to, sizeof(struct sockaddr_in))) { perror("binding name to datagram socket to"); exit(1); } /* receive message */ while (quitFlag) { n = recv(sockFrom, fromBuf, 1024); if (n < 0) perror("receiving datagram message"); fromBuf[n] = 0; /* null terminate */ switch (fromBuf[0]) { case 'E' : sscanf(fromBuf, "%c%s %d ", c, rcv_name, &toPort_no); printf("n=%d\n", n); printf("received msg=%s\n", fromBuf); printf("from host=%s, port=%d\n", rcv_name, &toPort_no); /* construct name of the socket to send to * gethostbyname() returns a structure including the network address * of the specified host from /etc/hosts. The port number is taken from * the cmd line * create name structure for the UNIX domain socket * use the name from cmd argument */ hp = gethostbyname(rcv_name); if (hp == 0) { fprintf(stderr, "%s: unknown host",rcv_name); exit(2); } bcopy(hp->h_addr, &to.sin_addr, hp->h_length); to.sin_family = AF_INET; to.sin_port = htons(toPort_no); /* replying with ack message */ sprintf(toBuf, "A%s\n", fromBuf); if (sendto(sockTo, toBuf, strlen(toBuf), 0, &to, sizeof(to)) < 0) perror("sending datagram message"); break; case 'q': quitFlag = 0; default: break; } } close(sockFrom); close(sockTo); }