Line data Source code
1 : /* SPDX-License-Identifier: GPL-3.0-or-later */
2 : /* Copyright 2026 Peter Csaszar */
3 :
4 : /**
5 : * @file socket.c
6 : * @brief POSIX TCP socket implementation.
7 : */
8 :
9 : #include "../socket.h"
10 :
11 : #include <sys/socket.h>
12 : #include <netinet/in.h>
13 : #include <netinet/tcp.h>
14 : #include <arpa/inet.h>
15 : #include <netdb.h>
16 : #include <unistd.h>
17 : #include <fcntl.h>
18 : #include <stdio.h>
19 : #include <string.h>
20 :
21 5 : int sys_socket_create(void) {
22 5 : int fd = socket(AF_INET, SOCK_STREAM, 0);
23 5 : if (fd < 0) return -1;
24 :
25 5 : int flag = 1;
26 5 : setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &flag, sizeof(flag));
27 :
28 5 : return fd;
29 : }
30 :
31 5 : int sys_socket_connect(int fd, const char *host, int port) {
32 : struct addrinfo hints, *res;
33 5 : memset(&hints, 0, sizeof(hints));
34 5 : hints.ai_family = AF_INET;
35 5 : hints.ai_socktype = SOCK_STREAM;
36 :
37 : char port_str[16];
38 5 : snprintf(port_str, sizeof(port_str), "%d", port);
39 :
40 5 : int rc = getaddrinfo(host, port_str, &hints, &res);
41 5 : if (rc != 0) return -1;
42 :
43 5 : rc = connect(fd, res->ai_addr, res->ai_addrlen);
44 5 : freeaddrinfo(res);
45 5 : return rc;
46 : }
47 :
48 21 : ssize_t sys_socket_send(int fd, const void *buf, size_t len) {
49 21 : return send(fd, buf, len, 0);
50 : }
51 :
52 16 : ssize_t sys_socket_recv(int fd, void *buf, size_t len) {
53 16 : return recv(fd, buf, len, 0);
54 : }
55 :
56 5 : int sys_socket_close(int fd) {
57 5 : return close(fd);
58 : }
59 :
60 0 : int sys_socket_set_nonblocking(int fd) {
61 0 : int flags = fcntl(fd, F_GETFL, 0);
62 0 : if (flags < 0) return -1;
63 0 : return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
64 : }
|