/* alternating bit sender for internet datagram demo */ #include #include #include #include #include #include #include #include #include #include #define DATA 1 #define ACK 2 struct Msg { struct sockaddr_in dst; struct sockaddr_in src; char msgtype; char buf[80]; char alternating_bit; }; void help_msg() { printf("format: absender -[dn] rcvhost rcvportno c1host c1portno\n"); printf(" option: n set the number of messages to be sent\n"); printf(" option: d set debug mode\n"); } void printsockaddr(struct sockaddr_in *arg) { struct hostent *hp; printf(" sockaddr_in: "); printf("Domain=%d, ", arg->sin_family); hp=gethostbyaddr((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)); } main(int argc, char *argv[]) { extern char *optarg; extern int optind; int option_exist = 0; int c; int debug = 1; char *rcvHost; /* receiver's host name */ int rcvPortNo; char *C1Host; /* channel C1's host name */ int C1PortNo; struct Msg mto; struct sockaddr_in c1addr; struct sockaddr_in from; struct hostent *hp; char hostname[80]; int i; int noOfPackets; int state = 1; /* process command line args */ while ((c=getopt(argc,argv,"dn:")) != EOF) { option_exist = 1; switch(c) { case 'n': if ((noOfPackets = atoi(optarg)) < 1) noOfPackets = 1; printf("The number of messages to be sent is %d\n", noOfPackets); break; case 'd': debug = 1; printf("set debug mode on\n"); break; case '?': help_msg(); exit (1); default: fprintf (stderr, "unrecognized arg >%s<\n", optarg); help_msg(); exit (1); } } rcvHost = argv[optind++]; rcvPortNo = atoi(argv[optind++]); C1Host = argv[optind++]; C1PortNo = atoi(argv[optind++]); /* create socket from which to read packet */ /* translate the domain name C1Host to its IP address using gethostbyname() assign IP address and portno to a sockaddr_in structure variable, here we use c1addr, for sending msg to C1. Make sure you use htons() before assign C1PortNo to sin_port field of the sockaddr_in variable */ /* fill the src field of mto with the sender's IP address and portno we use gethostname() to get current host name, then use gethostbyname to get the IP address. */ gethostname(hostname, sizeof(hostname)); hp = gethostbyname(hostname); if (hp == 0) { fprintf(stderr, "%s: unknown host",rcvHost); exit(2); } bcopy(hp->h_addr, &mto.src.sin_addr, hp->h_length); /* here I assume from is the struct sockaddr_in variable we used in bind() after getsockname() we have the assigned port no in from.sin_port. Here we just copy it over. */ mto.src.sin_family = AF_INET; mto.src.sin_port = from.sin_port; /* fill the dst fiedl of mto with the receiver's IP address and portno */ /* repeat sending for noOfPackets */ for (i=1; i