3 #ifdef HAVE_SYS_SOCKET_H
5 #include <osmocom/core/logging.h>
6 #include <osmocom/core/select.h>
7 #include <osmocom/core/socket.h>
9 #include <sys/socket.h>
10 #include <sys/types.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");
60 setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
62 /* Make sure to call 'listen' on a bound, connection-oriented sock */
63 if (connect0_bind1 == 1) {
74 int osmo_sock_init_ofd(struct osmo_fd *ofd, int family, int type, int proto,
75 const char *host, uint16_t port, int connect0_bind1)
79 sfd = osmo_sock_init(family, type, proto, host, port, connect0_bind1);
84 ofd->when = BSC_FD_READ;
86 rc = osmo_fd_register(ofd);
95 int osmo_sock_init_sa(struct sockaddr *ss, uint16_t type,
96 uint8_t proto, int connect0_bind1)
98 char host[NI_MAXHOST];
100 struct sockaddr_in *sin;
101 struct sockaddr_in6 *sin6;
104 /* determine port and host from ss */
105 switch (ss->sa_family) {
107 sin = (struct sockaddr_in *) ss;
108 sa_len = sizeof(struct sockaddr_in);
109 port = ntohs(sin->sin_port);
112 sin6 = (struct sockaddr_in6 *) ss;
113 sa_len = sizeof(struct sockaddr_in6);
114 port = ntohs(sin6->sin6_port);
120 s = getnameinfo(ss, sa_len, host, NI_MAXHOST,
121 NULL, 0, NI_NUMERICHOST);
123 perror("getnameinfo failed");
127 return osmo_sock_init(ss->sa_family, type, proto, host,
128 port, connect0_bind1);
131 static int sockaddr_equal(const struct sockaddr *a,
132 const struct sockaddr *b, unsigned int len)
134 struct sockaddr_in *sin_a, *sin_b;
135 struct sockaddr_in6 *sin6_a, *sin6_b;
137 if (a->sa_family != b->sa_family)
140 switch (a->sa_family) {
142 sin_a = (struct sockaddr_in *)a;
143 sin_b = (struct sockaddr_in *)b;
144 if (!memcmp(&sin_a->sin_addr, &sin_b->sin_addr,
145 sizeof(struct in_addr)))
149 sin6_a = (struct sockaddr_in6 *)a;
150 sin6_b = (struct sockaddr_in6 *)b;
151 if (!memcmp(&sin6_a->sin6_addr, &sin6_b->sin6_addr,
152 sizeof(struct in6_addr)))
159 /* determine if the given address is a local address */
160 int osmo_sockaddr_is_local(struct sockaddr *addr, socklen_t addrlen)
162 struct ifaddrs *ifaddr, *ifa;
164 if (getifaddrs(&ifaddr) == -1) {
165 perror("getifaddrs");
169 for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
172 if (sockaddr_equal(ifa->ifa_addr, addr, addrlen))
179 #endif /* HAVE_SYS_SOCKET_H */