/* receiver for internet datagram demo */ #include #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 toBuf[2048]; char fromBuf[2048]; 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 flags; /* 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. < 2048 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 (1) { n = recv(sockFrom, fromBuf, 2048, flags); if (n < 0) perror("receiving datagram message"); fromBuf[n] = 0; /* null terminate */ sscanf(fromBuf, "%s %d ", rcv_name, &toPort_no); printf("n=%d\n", n); printf("received msg="); for (i=0; ih_addr, &to.sin_addr, hp->h_length); */ /* in system V unix use memcpy */ memcpy(&to.sin_addr, hp->h_addr, hp->h_length); to.sin_family = AF_INET; to.sin_port = htons(toPort_no); /* replying with ack message */ sprintf(toBuf, "received message: %s\n", fromBuf); if (sendto(sockTo, toBuf, strlen(toBuf), 0, &to, sizeof(to)) < 0) perror("sending datagram message"); } close(sockFrom); close(sockTo); }