summaryrefslogtreecommitdiff
path: root/net.c
diff options
context:
space:
mode:
authorMichael Pavone <pavone@retrodev.com>2018-03-24 22:18:23 -0700
committerMichael Pavone <pavone@retrodev.com>2018-03-24 22:18:23 -0700
commit371d5418e6b1bfba88b55382b0a1b91d97023ae5 (patch)
tree26e75e6766ec3f43284b90f3ba5acbf72d78d646 /net.c
parent484e97a4e318d18b867acea7773853dfc7616a30 (diff)
parent15af9462392967b6adf7ba6ff4f7ff778cf10eb3 (diff)
Merge
--HG-- branch : nuklear_ui
Diffstat (limited to 'net.c')
-rw-r--r--net.c49
1 files changed, 49 insertions, 0 deletions
diff --git a/net.c b/net.c
new file mode 100644
index 0000000..eefc9cd
--- /dev/null
+++ b/net.c
@@ -0,0 +1,49 @@
+#include <sys/types.h>
+#include <ifaddrs.h>
+#include <netinet/in.h>
+#include "net.h"
+
+static uint8_t is_loopback(struct sockaddr_in *addr)
+{
+ return (addr->sin_addr.s_addr & 0xFF) == 127;
+}
+
+static void format_address(uint8_t *dst, struct sockaddr_in *addr)
+{
+ long ip = addr->sin_addr.s_addr;
+ dst[0] = ip;
+ dst[1] = ip >> 8;
+ dst[2] = ip >> 16;
+ dst[3] = ip >> 24;
+}
+
+uint8_t get_host_address(iface_info *out)
+{
+ struct ifaddrs *entries, *current, *localhost;
+ if (getifaddrs(&entries)) {
+ return 0;
+ }
+
+ for (current = entries; current; current = current->ifa_next)
+ {
+ if (current->ifa_addr && current->ifa_addr->sa_family == AF_INET) {
+ struct sockaddr_in *addr = (struct sockaddr_in *)current->ifa_addr;
+ if (is_loopback(addr)) {
+ localhost = current;
+ } else {
+ break;
+ }
+ }
+ }
+ if (!current && localhost) {
+ current = localhost;
+ }
+ uint8_t ret = 0;
+ if (current) {
+ ret = 1;
+ format_address(out->ip, (struct sockaddr_in *)current->ifa_addr);
+ format_address(out->net_mask, (struct sockaddr_in *)current->ifa_netmask);
+ }
+ freeifaddrs(entries);
+ return ret;
+} \ No newline at end of file