Harald Welte | f736559 | 2020-04-15 21:48:45 +0200 | [diff] [blame] | 1 | /* SPDX-License-Identifier: GPL-2.0 */ |
| 2 | #include <unistd.h> |
| 3 | #include <stdint.h> |
| 4 | #include <stdbool.h> |
| 5 | #include <stdlib.h> |
| 6 | #include <string.h> |
| 7 | #include <stdio.h> |
| 8 | #include <assert.h> |
| 9 | #include <sys/types.h> |
| 10 | #include <sys/socket.h> |
| 11 | #include <sys/stat.h> |
| 12 | #include <netdb.h> |
| 13 | |
| 14 | #include "internal.h" |
| 15 | |
| 16 | /*********************************************************************** |
| 17 | * Utility |
| 18 | ***********************************************************************/ |
| 19 | |
| 20 | bool sockaddr_equals(const struct sockaddr *a, const struct sockaddr *b) |
| 21 | { |
| 22 | const struct sockaddr_in *a4, *b4; |
| 23 | const struct sockaddr_in6 *a6, *b6; |
| 24 | |
| 25 | if (a->sa_family != b->sa_family) |
| 26 | return false; |
| 27 | |
| 28 | switch (a->sa_family) { |
| 29 | case AF_INET: |
| 30 | a4 = (struct sockaddr_in *) a; |
| 31 | b4 = (struct sockaddr_in *) b; |
| 32 | if (a4->sin_port != b4->sin_port) |
| 33 | return false; |
| 34 | if (a4->sin_addr.s_addr != b4->sin_addr.s_addr) |
| 35 | return false; |
| 36 | break; |
| 37 | case AF_INET6: |
| 38 | a6 = (struct sockaddr_in6 *) a; |
| 39 | b6 = (struct sockaddr_in6 *) b; |
| 40 | if (a6->sin6_port != b6->sin6_port) |
| 41 | return false; |
| 42 | if (memcmp(a6->sin6_addr.s6_addr, b6->sin6_addr.s6_addr, sizeof(b6->sin6_addr.s6_addr))) |
| 43 | return false; |
| 44 | break; |
| 45 | default: |
| 46 | assert(false); |
| 47 | } |
| 48 | |
| 49 | return true; |
| 50 | } |
| 51 | |
| 52 | struct addrinfo *addrinfo_helper(uint16_t family, uint16_t type, uint8_t proto, |
| 53 | const char *host, uint16_t port, bool passive) |
| 54 | { |
| 55 | struct addrinfo hints, *result; |
| 56 | char portbuf[6]; |
| 57 | int rc; |
| 58 | |
| 59 | snprintf(portbuf, sizeof(portbuf), "%u", port); |
| 60 | memset(&hints, 0, sizeof(hints)); |
| 61 | hints.ai_family = family; |
| 62 | hints.ai_socktype = type; |
| 63 | hints.ai_protocol = proto; |
| 64 | if (passive) |
| 65 | hints.ai_flags |= AI_PASSIVE; |
| 66 | |
| 67 | rc = getaddrinfo(host, portbuf, &hints, &result); |
| 68 | if (rc != 0) |
| 69 | return NULL; |
| 70 | |
| 71 | return result; |
| 72 | } |