From cac8f382588e33c83f533936ba980ed06d4340aa Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Roman=20Smr=C5=BE?= <roman.smrz@seznam.cz>
Date: Wed, 1 Dec 2021 22:10:39 +0100
Subject: Network: automatically find broadcast addresses

---
 src/Network/ifaddrs.c | 41 +++++++++++++++++++++++++++++++++++++++++
 src/Network/ifaddrs.h |  3 +++
 2 files changed, 44 insertions(+)
 create mode 100644 src/Network/ifaddrs.c
 create mode 100644 src/Network/ifaddrs.h

(limited to 'src/Network')

diff --git a/src/Network/ifaddrs.c b/src/Network/ifaddrs.c
new file mode 100644
index 0000000..37c3e00
--- /dev/null
+++ b/src/Network/ifaddrs.c
@@ -0,0 +1,41 @@
+#include "ifaddrs.h"
+
+#include <arpa/inet.h>
+#include <ifaddrs.h>
+#include <net/if.h>
+#include <stdlib.h>
+#include <sys/types.h>
+#include <endian.h>
+
+uint32_t * broadcast_addresses(void)
+{
+	struct ifaddrs * addrs;
+	if (getifaddrs(&addrs) < 0)
+		return 0;
+
+	size_t capacity = 16, count = 0;
+	uint32_t * ret = malloc(sizeof(uint32_t) * capacity);
+
+	for (struct ifaddrs * ifa = addrs; ifa; ifa = ifa->ifa_next) {
+		if (ifa->ifa_addr && ifa->ifa_addr->sa_family == AF_INET &&
+				ifa->ifa_flags & IFF_BROADCAST) {
+			if (count + 2 >= capacity) {
+				capacity *= 2;
+				uint32_t * nret = realloc(ret, sizeof(uint32_t) * capacity);
+				if (nret) {
+					ret = nret;
+				} else {
+					free(ret);
+					return 0;
+				}
+			}
+
+			ret[count] = ((struct sockaddr_in*)ifa->ifa_broadaddr)->sin_addr.s_addr;
+			count++;
+		}
+	}
+
+	freeifaddrs(addrs);
+	ret[count] = 0;
+	return ret;
+}
diff --git a/src/Network/ifaddrs.h b/src/Network/ifaddrs.h
new file mode 100644
index 0000000..06d26ec
--- /dev/null
+++ b/src/Network/ifaddrs.h
@@ -0,0 +1,3 @@
+#include <stdint.h>
+
+uint32_t * broadcast_addresses(void);
-- 
cgit v1.2.3