Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * @brief Give an url on format http://hostname/file or https://hostname/file
- * retrieve such file with a get. File is not saved.
- * @author Daniel Hilst Selli <danielhilst@gmail.com>
- */
- #include <stdio.h>
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <string.h>
- #include <stdlib.h>
- #include <netdb.h>
- #include <arpa/inet.h>
- #include <netinet/in.h>
- #define pexit(x) \
- do { \
- perror(x); \
- exit(EXIT_FAILURE); \
- } while (0)
- static char buf[BUFSIZ];
- int main(int argc, char **argv)
- {
- int sock;
- int error;
- int n = 3;
- int bytes = 0;
- struct addrinfo *resaddr;
- char *service;
- char *hostname;
- char *file;
- char *ptr;
- if (argc != 2) {
- fprintf(stderr, "Usage: %s {http|https}://HOSTNAME[/FILE]\n", argv[0]);
- exit(EXIT_FAILURE);
- }
- ptr = strchr(argv[1], ':');
- if (!ptr) {
- fprintf(stderr, "ERROR: Bad Service\n");
- fprintf(stderr, "Usage: %s {http|https}://HOSTNAME[/FILE]\n", argv[0]);
- exit(EXIT_FAILURE);
- }
- *ptr++ = '\0'; /* replace `://' to `\0\0\0' */
- *ptr++ = '\0'; /* terminating service string */
- *ptr++ = '\0';
- service = argv[1];
- printf("Service => %s\n", service);
- hostname = ptr;
- ptr = strchr(ptr, '/');
- if (ptr)
- *ptr++ = '\0'; /* replace `/' to `\0' terminating hostname string */
- printf("Hostname => %s\n", hostname);
- file = ptr ? ptr : "";
- printf("File => %s\n", file);
- error = getaddrinfo(hostname, service, NULL, &resaddr);
- if (error) {
- fprintf(stderr, "ERROR: %s\n", gai_strerror(error));
- exit(EXIT_FAILURE);
- }
- printf("IP Address => %s\n", inet_ntoa(((struct sockaddr_in *)resaddr->ai_addr)->sin_addr));
- /* create socket */
- sock = socket(resaddr->ai_family, resaddr->ai_socktype, resaddr->ai_protocol);
- if (sock == -1)
- pexit("socket");
- error = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(int));
- error = connect(sock, resaddr->ai_addr, resaddr->ai_addrlen);
- if (error)
- pexit("connect");
- puts("Connected!");
- freeaddrinfo(resaddr); /* free addrinfo linked list */
- snprintf(buf, BUFSIZ, "GET /%s\r\n", file);
- n = send(sock, buf, strlen(buf), MSG_WAITALL);
- if (n < 0)
- perror("send");
- printf("%s\n", buf);
- while ((n = recv(sock, buf, BUFSIZ, 0)) > 0) {
- bytes += n;
- printf("%d bytes transferred\n", bytes);
- /* printf("%.*s", n, buf); */
- }
- if (n == -1)
- pexit("recv");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement