Skip to content

Instantly share code, notes, and snippets.

@mycroft
Created January 25, 2020 13:08
Show Gist options
  • Save mycroft/730882b790e90ec5663b9681aca741c8 to your computer and use it in GitHub Desktop.
Save mycroft/730882b790e90ec5663b9681aca741c8 to your computer and use it in GitHub Desktop.
A C TCP connect with TCP_NODELAY & TCP_QUICKACK options
#include <errno.h>
#include <linux/tcp.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
int main()
{
const char* hostname = "216.58.195.68";
const char* portname = "http";
struct addrinfo hints;
struct addrinfo* res = 0;
int err;
int fd;
int one = 1;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = 0;
hints.ai_flags = AI_ADDRCONFIG;
err = getaddrinfo(hostname, portname, &hints, &res);
if (err != 0) {
fprintf(stderr, "failed to resolve remote socket address (err=%d)",err);
exit(1);
}
fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (fd == -1) {
fprintf(stderr, "%s\n", strerror(errno));
exit(1);
}
err = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
if (err != 0) {
fprintf(stderr, "Could not setsockopt: %s\n", strerror(errno));
exit(1);
}
err = setsockopt(fd, IPPROTO_TCP, TCP_QUICKACK, &one, sizeof(one));
if (err != 0) {
fprintf(stderr, "Could not setsockopt: %s\n", strerror(errno));
exit(1);
}
if (connect(fd,res->ai_addr, res->ai_addrlen) == -1) {
fprintf(stderr, strerror(errno));
exit(1);
}
write(fd, "GET / HTTP/1.0\n\r\n\r", 18);
close(fd);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment