3 #include <osmocom/core/logging.h>
4 #include <osmocom/core/select.h>
5 #include <osmocom/core/socket.h>
8 #include <sys/socket.h>
10 #include <netinet/in.h>
20 int osmo_sock_init(uint16_t family, uint16_t type, uint8_t proto,
21 const char *host, uint16_t port, int connect0_bind1)
23 struct addrinfo hints, *result, *rp;
27 sprintf(portbuf, "%u", port);
28 memset(&hints, 0, sizeof(struct addrinfo));
29 hints.ai_family = family;
30 hints.ai_socktype = type;
32 hints.ai_protocol = proto;
34 rc = getaddrinfo(host, portbuf, &hints, &result);
36 perror("getaddrinfo returned NULL");
40 for (rp = result; rp != NULL; rp = rp->ai_next) {
41 sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
44 if (connect0_bind1 == 0) {
45 if (connect(sfd, rp->ai_addr, rp->ai_addrlen) != -1)
48 if (bind(sfd, rp->ai_addr, rp->ai_addrlen) != -1)
56 perror("unable to connect/bind socket");
62 int osmo_sock_init_sa(struct sockaddr *ss, uint16_t type,
63 uint8_t proto, int connect0_bind1)
65 char host[NI_MAXHOST];
67 struct sockaddr_in *sin;
68 struct sockaddr_in6 *sin6;
71 /* determine port and host from ss */
72 switch (ss->sa_family) {
74 sin = (struct sockaddr_in *) ss;
75 sa_len = sizeof(struct sockaddr_in);
76 port = ntohs(sin->sin_port);
79 sin6 = (struct sockaddr_in6 *) ss;
80 sa_len = sizeof(struct sockaddr_in6);
81 port = ntohs(sin6->sin6_port);
86 fprintf(stderr, "==> PORT = %u\n", port);
88 s = getnameinfo(ss, sa_len, host, NI_MAXHOST,
89 NULL, 0, NI_NUMERICHOST);
91 perror("getnameinfo failed");
95 return osmo_sock_init(ss->sa_family, type, proto, host,
96 port, connect0_bind1);
99 static int sockaddr_equal(const struct sockaddr *a,
100 const struct sockaddr *b, socklen_t len)
102 struct sockaddr_in *sin_a, *sin_b;
103 struct sockaddr_in6 *sin6_a, *sin6_b;
105 if (a->sa_family != b->sa_family)
108 switch (a->sa_family) {
110 sin_a = (struct sockaddr_in *)a;
111 sin_b = (struct sockaddr_in *)b;
112 if (!memcmp(&sin_a->sin_addr, &sin_b->sin_addr,
113 sizeof(struct in_addr)))
117 sin6_a = (struct sockaddr_in6 *)a;
118 sin6_b = (struct sockaddr_in6 *)b;
119 if (!memcmp(&sin6_a->sin6_addr, &sin6_b->sin6_addr,
120 sizeof(struct in6_addr)))
127 /* determine if the given address is a local address */
128 int osmo_sockaddr_is_local(struct sockaddr *addr, socklen_t addrlen)
130 struct ifaddrs *ifaddr, *ifa;
132 if (getifaddrs(&ifaddr) == -1) {
133 perror("getifaddrs");
137 for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
138 if (sockaddr_equal(ifa->ifa_addr, addr, addrlen))