A TCP client in C
socket, connect, write, read, close — the whole client in five calls.
#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
int fetch(const char *ip, int port) {
int fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0) {
return 0;
}
struct sockaddr_in addr;
memset(&addr, 0, sizeof addr);
addr.sin_family = AF_INET;
addr.sin_port = htons((unsigned short) port);
inet_pton(AF_INET, ip, &addr.sin_addr);
if (connect(fd, (struct sockaddr *) &addr, sizeof addr) != 0) {
close(fd);
return 0;
}
const char *request = "GET /healthz HTTP/1.0\r\n\r\n";
write(fd, request, strlen(request));
char buffer[256];
ssize_t n = read(fd, buffer, sizeof buffer - 1);
if (n > 0) {
buffer[n] = '\0';
printf("%s", buffer);
}
close(fd);
return n > 0;
}
How it works
AF_INETwithSOCK_STREAMmeans IPv4 TCP.- The port must be converted with
htons. - Every descriptor is closed on the way out.
Keywords and builtins used here
charconstfetchifintreturnshortsizeofsockaddrsockaddr_inssize_tstructunsigned
The run, in numbers
- Lines
- 35
- Characters to type
- 713
- Tokens
- 210
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 115 seconds.
Step 1 of 1 in Sockets, step 13 of 14 in Systems programming.