Files
mcde/lib/McdeSys/net.c
T
lotherkandClaude Opus 5.5 7aab59d334 mcde: McdeSys: network interfaces, volume, Bluetooth (NetBSD and Linux)
mcde_sys_interfaces (getifaddrs; Wi-Fi and SSID from the backend: the
SIOCG80211NWID ioctl on NetBSD, /sys/class/net and iw(8) on Linux),
mcde_sys_volume_get/set/mute (PulseAudio's pactl where a server answers,
else mixerctl(1) on NetBSD, amixer(1) on Linux), mcde_sys_bluetooth and
_power (btconfig(8), bluetoothctl(1)).  mcde_sys_capture reads a tool's
output to the end.  test_sysinfo only reads: on the Linux host Wi-Fi with
its SSID, 75 %, hci0 on; in the NetBSD VM wm0 wired with its address, no
mixer, no Bluetooth -- both PASS.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 08:07:43 +00:00

88 lines
2.3 KiB
C

/*
* net.c -- MCDE: the network interfaces (McdeSys.h, "Network")
*
* Copyright (c) 2026 The Makronix project. GNU LGPL 2.0 or later, as CDE.
*
* getifaddrs(3) -- not POSIX, but the same on NetBSD (where it comes from)
* and on Linux -- gives the interfaces and their addresses; whether one is
* Wi-Fi, and which network it has joined, the backend tells
* (mcde_sys_if_kind). The loopback is left out.
*/
#define _NETBSD_SOURCE /* getifaddrs(3) on NetBSD */
#ifndef _DEFAULT_SOURCE
#define _DEFAULT_SOURCE /* and on Linux */
#endif
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <ifaddrs.h>
#include <net/if.h>
#include <netdb.h>
#include <netinet/in.h>
#include <Mcde/McdeSys.h>
#include "private.h"
static McdeSysInterface *
Find(McdeSysInterface *ifs, size_t n, const char *name)
{
size_t i;
for (i = 0; i < n; i++)
if (strcmp(ifs[i].name, name) == 0)
return &ifs[i];
return NULL;
}
int
mcde_sys_interfaces(McdeSysInterface *ifs, size_t max)
{
struct ifaddrs *all, *a;
size_t n = 0;
if (getifaddrs(&all) != 0)
return mcde_sys_fail(MCDE_SYS_EFAIL, "No network interfaces.");
for (a = all; a != NULL; a = a->ifa_next) {
McdeSysInterface *it;
int fam;
if (a->ifa_flags & IFF_LOOPBACK)
continue;
if ((it = Find(ifs, n, a->ifa_name)) == NULL) {
if (n >= max)
continue;
it = &ifs[n++];
memset(it, 0, sizeof *it);
snprintf(it->name, sizeof it->name, "%s", a->ifa_name);
it->kind = mcde_sys_if_kind(it->name, it->ssid,
sizeof it->ssid);
}
if (a->ifa_addr == NULL || !(a->ifa_flags & IFF_UP))
continue;
fam = a->ifa_addr->sa_family;
/* an IPv4 address first; an IPv6 one only if there is none,
* and not the link-local one every interface has */
if (fam == AF_INET || (fam == AF_INET6 && it->address[0] == '\0')) {
char host[NI_MAXHOST];
if (fam == AF_INET6 && IN6_IS_ADDR_LINKLOCAL(
&((struct sockaddr_in6 *) a->ifa_addr)->sin6_addr))
continue;
if (getnameinfo(a->ifa_addr, fam == AF_INET ?
sizeof(struct sockaddr_in) :
sizeof(struct sockaddr_in6), host, sizeof host,
NULL, 0, NI_NUMERICHOST) == 0) {
snprintf(it->address, sizeof it->address, "%s",
host);
it->up = 1;
}
}
}
freeifaddrs(all);
return (int) n;
}