Skip to content

Instantly share code, notes, and snippets.

@jq2
Created August 24, 2018 04:00
Show Gist options
  • Save jq2/a0436a596f37f8df4963161c81e9a555 to your computer and use it in GitHub Desktop.
Save jq2/a0436a596f37f8df4963161c81e9a555 to your computer and use it in GitHub Desktop.
Sending HTTP requests in C language
/*
@date: Fri Aug 24 00:32:44 -03 2018
@author: Dan Morris A.K.A jq2
@filename: ex0.c
@last_updated: Fri Aug 24 00:53:47 -03 2018
@description: Enviando requisições HTTP GET usando a API de soquetes do Unix/BSD (Berkeley sockets).
Exemplo desenvolvido para o 'Hacking-BR - Grupo de estudos' no Facebook.
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main (int argc, char *argv[]) {
struct sockaddr_in in;
struct sockaddr_storage peer_addr;
socklen_t peer_addr_len;
int sock, port = atoi(argv[1]);
ssize_t nread;
char buf[1024];
in.sin_family = AF_INET;
in.sin_port = htons(port);
in.sin_addr.s_addr = htonl(INADDR_ANY);
sock = socket(PF_INET, SOCK_STREAM, 0);
int connect_result = connect(sock, (struct sockaddr *) &in, sizeof(in));
send(sock, "GET / HTTP/1.1\r\n", 17, 0);
for (;;) {
peer_addr_len = sizeof(struct sockaddr_storage);
nread = recvfrom(sock, buf, 1024, 0, (struct sockaddr *) &peer_addr, &peer_addr_len);
if (nread == -1) {
printf("Exiting...\n");
exit(255);
break;
}
else {
printf("Recvfrom: %d\n", nread);
printf("Message: %s\n", buf);
break;
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment