/* sender for internet stream demo */ #include #include #include #include #include #include #include #include #define ENDPACKET "end" #define MAXLINE 256 help_msg() { printf("format: spr -[cdnr] url\n"); printf(" Option: c save in cache file format\n"); printf(" Option: d set debug mode\n"); printf(" Option: n set the number of retrievals\n"); printf(" Option: r set the byte range for retrieval\n"); } getline(s, lim) char s[]; int lim; { int c, i; for (i=0; i%s<\n", optarg); help_msg(); exit (1); } } url = (char *) argv[optind++]; printf("url=%s\n", url); parseUrl(url, hostfield, domainname, port, uri); printf("url=%s\nhostfield=%s\ndomainname=%s\nport=%s\nuri=%s\n", url, hostfield, domainname, port, uri); if (debug) printf("The web server's host name is %s, port_no=%s\n", domainname, port); /* 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(domainname); if (hp == 0) { fprintf(stderr, "%s: unknown host",rcv_name); exit(2); } memcpy(&server.sin_addr, hp->h_addr, hp->h_length); server.sin_family = AF_INET; server.sin_port = htons(atoi(port)); if (connect(sock, &server, sizeof(server)) < 0) { perror("connecting stream socket"); exit(1); } /* formulate request */ sprintf(request, "GET %s HTTP/1.1\nRange: bytes=%s\nHost: %s\n\n", uri, byteRange, hostfield); length = strlen(request); /* create data file */ fd= open(outFile, O_WRONLY | O_CREAT, 00644); getByteRange(byteRange, &startByte, &endByte); if (debug) printf("startByte=%d, endByte=%d\n", startByte, endByte); size = endByte - startByte + 1; /*send message */ if (write(sock, request, length) < 0) perror("writing on stream socket"); if ((nBytesRcvd=read(sock, fromBuf, sizeof(fromBuf))) < 0) { perror("reading on stream socket"); exit(1); } dataPtr = getDataSize(fromBuf, &fileLength); header_length = dataPtr - fromBuf; length = nBytesRcvd - header_length; printf("nBytesRcvd=%d, http header length=%d\n", nBytesRcvd, header_length); if (debug) printf("fileLength=%d\n", fileLength); if (cache) { write(fd, fromBuf, nBytesRcvd); } else { write(fd, dataPtr, length); } if (debug) printf("packet %d: size=%d\n", i++, nBytesRcvd); size -= length; while(size>0) { // more packets coming if ((nBytesRcvd=read(sock, fromBuf, sizeof(fromBuf))) < 0) { perror("reading on stream socket"); exit(1); } if (nBytesRcvd == 0) { printf("receiver breaks the connection, exiting...\n"); break; } write(fd, fromBuf, nBytesRcvd); if (debug) printf("packet %d: with %d bytes\n", i++, nBytesRcvd); size -= nBytesRcvd; } close(fd); close(sock); }