Created
August 16, 2020 10:29
-
-
Save sidsbrmnn/96443ac6f6c72a971a46d29e32150d67 to your computer and use it in GitHub Desktop.
This file contains 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 <arpa/inet.h> | |
#include <errno.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <strings.h> | |
#include <sys/socket.h> | |
#include <unistd.h> | |
#define PORT 80 | |
#define MAXLINE 4096 | |
int main(int argc, char const *argv[]) { | |
int sockfd; | |
int sendbytes, recvbytes; | |
struct sockaddr_in servaddr; | |
char sendline[MAXLINE]; | |
char recvline[MAXLINE]; | |
if (argc != 2) { | |
printf("usage: %s <url>", argv[0]); | |
exit(1); | |
} | |
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { | |
printf("error: unable to create the socket"); | |
exit(1); | |
} | |
bzero(&servaddr, sizeof(servaddr)); | |
servaddr.sin_family = AF_INET; | |
servaddr.sin_port = htons(PORT); | |
if (inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <= 0) { | |
printf("error: unable to translate ip %s", argv[1]); | |
exit(1); | |
} | |
if (connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) { | |
printf("error: connection failed"); | |
exit(1); | |
} | |
sprintf(sendline, "GET / HTTP/1.1\r\n\r\n"); | |
sendbytes = strlen(sendline); | |
if (write(sockfd, sendline, sendbytes) != sendbytes) { | |
printf("error: write error"); | |
exit(1); | |
} | |
memset(recvline, 0, MAXLINE); | |
while ((recvbytes = read(sockfd, recvline, MAXLINE - 1)) > 0) { | |
printf("%s", recvline); | |
} | |
if (recvbytes < 0) { | |
printf("error: read error"); | |
exit(1); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment