Skip to content

Instantly share code, notes, and snippets.

@jiahuif
Created April 23, 2021 22:45
Show Gist options
  • Save jiahuif/03794bfbb07b7dc35a4cdab7e6abf707 to your computer and use it in GitHub Desktop.
Save jiahuif/03794bfbb07b7dc35a4cdab7e6abf707 to your computer and use it in GitHub Desktop.
test_204.c
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#define BUF_SIZE 1024
int main(int argc, char *argv[]) {
const char hostname[] = "www.gstatic.com";
const char port[] = "80";
const char request[] = "GET /generate_204 HTTP/1.1\r\n"
"Host: www.gstatic.com\r\n"
"Accept: */*\r\n"
"Connection: close\r\n"
"\r\n";
const size_t len = sizeof(request) - 1;
const char http_1_1[] = "HTTP/1.1";
const size_t http_1_1_len = sizeof(http_1_1) - 1;
char buf[BUF_SIZE];
ssize_t nread;
int sfd, s;
struct addrinfo *result, *rp;
struct addrinfo hints = {
.ai_family = AF_UNSPEC,
.ai_socktype = SOCK_STREAM,
.ai_flags = AI_V4MAPPED | AI_ADDRCONFIG,
.ai_protocol = 0,
};
s = getaddrinfo(hostname, port, &hints, &result);
if (s != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
return EXIT_FAILURE;
}
for (rp = result; rp != NULL; rp = rp->ai_next) {
sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (sfd == -1)
continue;
if (connect(sfd, rp->ai_addr, rp->ai_addrlen) != -1)
break; /* Success */
close(sfd);
}
freeaddrinfo(result); /* No longer needed */
if (rp == NULL) { /* No address succeeded */
fprintf(stderr, "Could not connect\n");
return EXIT_FAILURE;
}
if (write(sfd, request, len) != len) {
fprintf(stderr, "partial/failed write\n");
return EXIT_FAILURE;
}
if (shutdown(sfd, SHUT_WR) != 0) {
perror("shutdown");
return EXIT_FAILURE;
}
nread = read(sfd, buf, BUF_SIZE);
if (nread == -1) {
perror("read");
return EXIT_FAILURE;
}
if (nread < 12 || strncmp(buf, http_1_1, http_1_1_len) != 0) {
fprintf(stderr, "bad http response");
return EXIT_FAILURE;
}
const char *status = buf + 9;
if (status[0] != '2' || status[1] != '0' || status[2] != '4') {
fprintf(stderr, "http status: %.3s\n", status);
return EXIT_FAILURE;
}
while (nread != 0 && nread == -1) {
nread = read(sfd, buf, BUF_SIZE);
}
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment