Socket HTTP GET JSON code extractor with timeouts in C

C
#define _POSIX_C_SOURCE 200809L
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int http_json_code(const char *ip, int port, const char *path, char *buf, size_t cap) {
    struct sockaddr_in a = {.sin_family = AF_INET, .sin_port = htons(port)};
    if (inet_pton(AF_INET, ip, &a.sin_addr) != 1) return -1; int fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd < 0) return -1;
    setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &(struct timeval){2, 0}, sizeof(struct timeval));
    if (connect(fd, (struct sockaddr *)&a, sizeof a) != 0) return close(fd), -1;
    dprintf(fd, "GET %s HTTP/1.0\r\nHost: %s\r\nConnection: close\r\n\r\n", path, ip);
    ssize_t n = 0, r;
    while (n < (ssize_t)cap - 1 && (r = read(fd, buf + n, cap - 1 - n)) > 0) n += r;
    close(fd); buf[n] = '\0';
    char *body = strstr(buf, "\r\n\r\n");
    char *code = body ? strstr(body + 4, "\"code\":") : NULL;
    return code ? (int)strtol(code + 7, NULL, 10) : -1;
}