/* sender for internet stream demo */ #include #include #include #include #define ENDPACKET "end" help_msg() { printf("format: inetsts -[dn] hostname portno\n"); printf(" option: n set the number packet to be sent\n"); printf(" d set debug mode\n"); } main(argc, argv) int argc; char *argv[]; { int sock; struct sockaddr_in server; struct hostent *hp, *gethostbyname(); int n = 1; int i; char buf[1024]; extern char *optarg; extern int optind; int option_exist = 0; int c; int debug = 0; char *rcv_name; /* receiver's socket name */ int port_no; fd_set fdvar; /* process command line args */ while ((c=getopt(argc,argv,"dn:")) != EOF) { option_exist = 1; switch(c) { case 'd': debug = 1; if (debug) printf("turn on debug mode.\n"); break; case 'n': if ((n = atoi(optarg)) < 1) n = 1; if (debug) printf("The number packet to be sent is %d\n", n); break; case '?': help_msg(); exit (1); default: fprintf (stderr, "unrecognized arg >%s<\n", optarg); help_msg(); exit (1); } } printf("argc=%d\n", argc); if (argc < 3) { fprintf (stderr, "%s: require hostname and portno.\n", argv[0]); help_msg(); exit (1); } rcv_name = argv[optind++]; if ((port_no = atoi(argv[optind])) < 1025) port_no = 1025; if (debug) printf("The receiver's host name is %s, port_no=%d\n", rcv_name, port_no); /* create socket on which to sent */ sock = socket(AF_INET, SOCK_STREAM, 0); if (sock < 0) { perror("opening stream socket"); exit(1); } /* 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 internet 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, &server.sin_addr, hp->h_length); server.sin_family = AF_INET; server.sin_port = htons(port_no); if (connect(sock, &server, sizeof(server)) < 0) { perror("connecting stream socket"); exit(1); } /*send message */ for (i=0; i< n; i++) { sprintf(buf, "packet %d,",i); FD_SET(sock, &fdvar); if (select(sock+1, 0, &fdvar, 0, 0) < 0) perror("select error"); else printf("ok for writing %s\n", buf); if (write(sock, buf, strlen(buf)) < 0) perror("writing on stream socket"); } if (read(sock, buf, sizeof(buf)) < 0) perror("writing on stream socket"); close(sock); }