File: sock.c

package info (click to toggle)
linuxptp 4.2-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 1,536 kB
  • sloc: ansic: 26,119; sh: 92; makefile: 87
file content (58 lines) | stat: -rw-r--r-- 1,312 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
 * @file sock.c
 * @note Copyright (C) 2020 Richard Cochran <richardcochran@gmail.com>
 * @note SPDX-License-Identifier: GPL-2.0+
 */
#include <netdb.h>
#include <netinet/tcp.h>
#include <string.h>
#include <unistd.h>

#include "print.h"
#include "sock.h"

typedef void *so_t;

int sock_open(const char *server, const char *port)
{
	int i, err, family[2] = { AF_INET, AF_INET6 }, fd;
	struct addrinfo	hints, *result = NULL;
	socklen_t addrlen;

	memset(&hints, 0, sizeof(hints));
	hints.ai_flags = AI_CANONNAME;
	hints.ai_socktype = SOCK_STREAM;

	for (i = 0; i < 2; i++) {
		hints.ai_family = family[i];
		err = getaddrinfo(server, port, &hints, &result);
		if (err) {
			pr_debug("%s: getaddrinfo failed family %d: %s",
				 __func__, hints.ai_family, gai_strerror(err));
			result = NULL;
		} else {
			break;
		}
	}
	if (!result) {
		return -1;
	}

	addrlen = (socklen_t) result->ai_addrlen;
	pr_debug("%s: connecting to server %s canonical %s",
		 __func__, server, result->ai_canonname);

	fd = socket(result->ai_family, SOCK_STREAM, result->ai_protocol);
	if (fd < 0) {
		pr_err("%s: socket failed: %m", __func__);
		goto failed;
	}
	if (connect(fd, result->ai_addr, addrlen) < 0) {
		pr_err("%s: connect failed: %m", __func__);
		close(fd);
		fd = -1;
	}
failed:
	freeaddrinfo(result);
	return fd;
}