Last active
September 13, 2021 22:36
-
-
Save dmamills/d69a81ea9b79a6c319c09ec1844bdbec to your computer and use it in GitHub Desktop.
basic HTTP get unix socket
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <strings.h> | |
#include <unistd.h> | |
#include <netinet/in.h> | |
#include <netinet/tcp.h> | |
#include <sys/socket.h> | |
#include <sys/types.h> | |
#include <fcntl.h> | |
#include <netdb.h> | |
#define PORT 80 | |
#define CHUNK_SIZE 1024 | |
int main(int argc, char **argv) { | |
int sockfd; // file descriptor for socket | |
int nread = 0; // number of bytes read from current recv call | |
int totalRead = 0; // number of bytes read in total | |
char buffer[CHUNK_SIZE]; // buffer for current chunk | |
char totalBuff[CHUNK_SIZE * 4]; // big boy for holding all chunks | |
char* message = "GET / HTTP/1.1\r\nHost: example.com\r\nAccept: */*\r\nConnection: close\r\n\r\n"; // Our "GET" request | |
if(argc == 1) { | |
printf("Usage ./get <hostname>\n"); | |
return 1; | |
} | |
struct hostent *hp; // struct holding host name information | |
struct sockaddr_in addr; // struct for holding socket information like ip/port | |
//convert url to ip address, pulled from command line args | |
hp = gethostbyname(argv[1]); | |
if(hp == NULL) { | |
printf("Unable to get hostname\n"); | |
return 1; | |
} | |
//copy ip from hp struct to sockaddr_in struct | |
bcopy(hp->h_addr, &addr.sin_addr, hp->h_length); | |
addr.sin_port = htons(PORT); | |
addr.sin_family = AF_INET; | |
// create socket | |
int on = 1; | |
sockfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); | |
setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, (const char*)&on, sizeof(int)); | |
if(sockfd == -1) { | |
printf("Couldnt init socket\n"); | |
return 1; | |
} | |
//setup socket to connect | |
if(connect(sockfd, (struct sockaddr*)&addr, sizeof (struct sockaddr_in)) == -1) { | |
printf("unable to connect\n"); | |
return 1; | |
} | |
// send our GET request | |
write(sockfd, message, strlen(message)); | |
bzero(totalBuff, CHUNK_SIZE * 4); | |
fcntl(sockfd, F_SETFL, O_NONBLOCK); | |
// start recieving data | |
while(1) { | |
bzero(buffer, CHUNK_SIZE); | |
if((nread = recv(sockfd, buffer, CHUNK_SIZE, MSG_DONTWAIT)) < 0) { | |
usleep(1000000); | |
} else if(nread == 0) { | |
//done reading | |
break; | |
} else { | |
//Copy over read bytes into total buffer | |
memcpy(totalBuff + totalRead, buffer, nread); | |
totalRead += nread; | |
} | |
} | |
// Print out what we recieved | |
printf("Total bytes read: %d\n", totalRead); | |
printf("Got:\n%s", totalBuff); | |
shutdown(sockfd, SHUT_RDWR); | |
close(sockfd); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment