Skip to content

Instantly share code, notes, and snippets.

@domdomegg
Last active January 7, 2020 12:44
Show Gist options
  • Save domdomegg/88b2af22acfb3fb854e67402af504e5c to your computer and use it in GitHub Desktop.
Save domdomegg/88b2af22acfb3fb854e67402af504e5c to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netdb.h>
int main(int argc, char* argv[]) {
// Create an internet socket
int mySocket = socket(AF_INET, SOCK_STREAM, 0);
// Set up addrinfo hints object so getaddrinfo knows we're talking about getting an IPv4 address
struct addrinfo hints;
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = 0;
hints.ai_flags = AI_PASSIVE;
// Get address (IPv4) info for google.com on port 80, and store it in the addr variable
struct addrinfo *addr;
getaddrinfo("google.com", "80", &hints, &addr);
// Tell mySocket to connect using this address info (not send anything yet, just open a 'door' to Google)
connect(mySocket, addr->ai_addr, sizeof(struct sockaddr_in));
// Store the HTTP GET request to send later in a string
// (You can also try sending a 'HEAD' request, which makes the webserver just return the headers and not the actual content)
char* http_get = "GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: close\r\n\r\n";
// Write the HTTP GET request to the socket, actually sending it to Google
write(mySocket, http_get, strlen(http_get));
// Open the socket in read mode, and open the output.html file in write mode (will create if not exists)
FILE* data = fdopen(mySocket, "r");
FILE* output = fopen("output.html", "w");
int c;
if (data) {
// While characters coming from the data file are not EOF (special character to indicate end of file)
while ((c = getc(data)) != EOF) {
// Put the character in the output file (basically we're copying the stuff we're reading from the data file - which is what Google is sending - to the output file)
fputc(c, output);
}
} else {
printf("Failed to connect - Alexa, play despacito");
exit(1);
}
// Close all the things! (so we don't keep the files/connection open once we're not using them)
fclose(data);
fclose(output);
close(mySocket);
// Free all the things (well, the thing...). Stops memory leaks (where we allocate memory but don't end up actually using it)
// Not really necessary here as the program exits anyways, but in a real program where we'd go on to do other stuff we'd need to do it
freeaddrinfo(addr);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment