Standard library · Network

net.wifi

The Wi-Fi network the machine is on: name, access point, security and signal, with a trust check for clients that connect a VPN on untrusted networks.

import net.wifi

net.wifi tells a program which Wi-Fi network the machine is on and how that network is protected. It was written for VPN clients that offer "connect automatically on untrusted Wi-Fi", but anything that cares about the network it runs on can use it. It only reads: it never scans on its own, never joins a network and never asks for passwords.

Each platform uses what the system already has, loaded when it is first needed, so importing the package adds no build dependency and a missing piece makes a call return an empty or unknown result instead of failing:

PlatformSourceNotes
LinuxNetworkManager over the system D-Bus (through libgio-2.0), then iw, then /sys/class/netWithout NetworkManager the security comes from iw dev X scan dump, which may be empty until the system scans.
Windowswlanapi.dll, loaded only from System32Since Windows 11 24H2 reading the current network needs location access for desktop apps. Without it the interface is still reported as connected, but ssid_known is false and security is Unknown, so Classify answers Unknown and the caller decides. There is no workaround.
macOSCoreWLANSince macOS 14 the network name needs Location Services permission; without it ssid_known is false and reason says why. A station or ad hoc (IBSS) interface counts as connected; an interface acting as a hotspot, or in no mode, counts as disconnected.
Other systemsnoneSupported is false and Current reports NoWifi.

Things to know:

  • The trusted list wins. A network that matches a trusted entry is Trusted even when it is open, OWE or WEP: a user may trust their own open network. The rules below apply only when no trusted entry matches.
  • Unknown is not untrusted. When no trusted entry matches and the system hides the network name, Classify answers Unknown unless the network is open, has only WEP or uses OWE (anyone can join those). Decide yourself what an unknown network means; the package never guesses for you.
  • Two kinds of trusted entry. An entry shaped like an access point address (six pairs of hex digits joined by colons, such as de:ad:be:ef:00:01) matches only the BSSID, without case. Every other entry matches only the network name, exactly: SSIDs are case sensitive, so "Home" and "home" are different networks.
  • A name with a NUL byte is not a name. Such an SSID could be cut short and match a trusted entry, so ssid stays empty and ssid_known is false.
  • You own the strings. A Status from Current, Interfaces, ParseIwLink or ParseWlanConnection owns its interface, ssid and bssid text. Release it with FreeStatus, or a whole list with FreeStatuses, when you are done; backend and reason are fixed text and need nothing. Never pass a Status you built yourself to these functions.
  • Polling, not events. Call Current every few seconds and compare with Changed; it ignores the signal so a moving laptop does not look like a new network.
  • The parsers are public. ParseIwLink, ParseIwScan, ParseWlanConnection and the SecurityFrom functions are what the backends use, exposed so tests and tools can feed them recorded output.

The current network

Current returns one Status: the connected interface if there is one, otherwise a disconnected one, otherwise an interface whose state could not be read (Unknown, with the cause in reason). Only when no wireless interface exists at all is the state NoWifi. Check state first, then ssid_known before you use ssid. Interfaces returns every wireless interface instead.

net-wifi-guide-current.salam
import net.wifi

func main:
    s := wifi.Current()
    switch s.state:
        wifi.State.Connected:
            if s.ssid_known:
                println "on Wi-Fi", s.ssid, "security", wifi.SecurityName(s.security)
            else:
                println "on Wi-Fi, name not available:", s.reason
            end
            break
        end
        wifi.State.Disconnected:
            println "Wi-Fi is not connected"
            break
        end
        wifi.State.NoWifi:
            println "this machine has no Wi-Fi"
            break
        end
        wifi.State.Unknown:
            println "cannot tell:", s.reason
            break
        end
    end
    wifi.FreeStatus(s)
end

Trusted and untrusted networks

Classify takes the list of networks the user trusts and returns a Trust. A match on the list is always Trusted, even for an open network. When nothing on the list matches, Untrusted means the network is known, or it is open, OWE or WEP, and Unknown means the system did not say which network it is. NotWifi means the machine is not on Wi-Fi at all, for example on a cable. IsUntrusted is the short form for the one answer that should start a VPN.

net-wifi-guide-trust.salam
import net.wifi

func decide(s: wifi.Status, trusted: Vector<str>): str:
    switch wifi.Classify(s, trusted):
        wifi.Trust.Untrusted: ret "connect the VPN" end
        wifi.Trust.Trusted: ret "stay as you are" end
        wifi.Trust.Unknown: ret "ask the user" end
        wifi.Trust.NotWifi: ret "not on Wi-Fi" end
    end
    ret ""
end

func main:
    mut trusted := Vector {} as Vector<str>
    defer trusted.Free()
    trusted.Push("Home")
    println decide(wifi.Status {
        state = wifi.State.Connected,
        ssid = "Home",
        ssid_known = true,
        security = wifi.Security.Wpa2
    }, trusted)
    println decide(wifi.Status {
        state = wifi.State.Connected,
        ssid = "Airport",
        ssid_known = true,
        security = wifi.Security.Open
    }, trusted)
    println decide(
        wifi.Status { state = wifi.State.Connected, security = wifi.Security.Wpa2 }, trusted
    )
    println decide(
        wifi.Status { state = wifi.State.Connected, security = wifi.Security.Open }, trusted
    )
    println decide(wifi.Status { state = wifi.State.NoWifi }, trusted)
end
Outputstay as you are connect the VPN ask the user connect the VPN not on Wi-Fi

Watching for a new network

Keep the last Status, read a new one on a timer and act only when Changed says so. Free the one you no longer keep. Run the loop on a worker thread in a desktop app, so a slow D-Bus or wlanapi answer never blocks the window.

net-wifi-guide-watch.salam
import net.wifi
import sync

func main:
    mut trusted := Vector {} as Vector<str>
    defer trusted.Free()
    trusted.Push("Home")
    trusted.Push("Office")
    mut last := wifi.Current()
    println "starting on a network that is", wifi.TrustName(wifi.Classify(last, trusted))
    repeat 10:
        now := wifi.Current()
        if wifi.Changed(last, now):
            if wifi.IsUntrusted(now, trusted):
                println "untrusted network, starting the VPN"
            else:
                println "network is", wifi.TrustName(wifi.Classify(now, trusted))
            end
            wifi.FreeStatus(last)
            last = now
        else:
            wifi.FreeStatus(now)
        end
        sync.SleepMs(3000)
    end
    wifi.FreeStatus(last)
end

Types

State

enum State
Whether a Wi-Fi interface is connected: Unknown, NoWifi, Disconnected or Connected.
NameTypeDescription
UnknownThe backend could not tell, for example an interface NetworkManager does not manage and iw is missing, a failed read, or a network that changed while it was being read.
NoWifiThe machine has no wireless interface, or the platform has no Wi-Fi backend.
DisconnectedThere is a Wi-Fi interface but it is not associated with a network as a client, Wi-Fi is turned off, or (on macOS) the interface is acting as a hotspot.
ConnectedThe interface is associated with a network.
net-wifi-State.salam
import net.wifi

func main:
    each st in [
        wifi.State.Unknown, wifi.State.NoWifi, wifi.State.Disconnected, wifi.State.Connected
    ]:
        s := wifi.Status { state = st }
        println wifi.StateName(st), s.IsConnected()
    end
    println wifi.TrustName(wifi.Trust.NotWifi),
        wifi.TrustName(wifi.Trust.Trusted),
        wifi.TrustName(wifi.Trust.Untrusted)
end
Outputunknown false no-wifi false disconnected false connected true not-wifi trusted untrusted

Security

enum Security
How the network protects its traffic, from the weakest to the strongest: Open, Owe, Wep, Wpa, Wpa2, Wpa3 and Enterprise, or Unknown.
NameTypeDescription
UnknownThe backend did not report the security, or reported a mode this package does not know.
OpenNo encryption: anyone nearby can join and read the traffic.
OweOpportunistic Wireless Encryption (Enhanced Open): encrypted, but anyone can join.
WepWEP, broken for many years.
WpaWPA with a shared password.
Wpa2WPA2 with a shared password.
Wpa3WPA3 (SAE) with a shared password, including WPA2/WPA3 transition networks.
Enterprise802.1X login with a user account (WPA, WPA2 or WPA3 Enterprise).
net-wifi-Security.salam
import net.wifi

func main:
    println wifi.SecurityName(wifi.SecurityFromNm(1, 0, 0x188))
    println wifi.SecurityName(wifi.SecurityFromNm(1, 0, 0x488))
    println wifi.SecurityName(wifi.SecurityFromNm(1, 0, 0x288))
    println wifi.SecurityName(wifi.SecurityFromNm(0, 0, 0))
    println wifi.SecurityName(wifi.SecurityFromWlan(7, 4, false))
    println wifi.SecurityName(wifi.SecurityFromWlan(9, 4, false))
    println wifi.SecurityName(wifi.SecurityFromWlan(1, 0, false))
    println wifi.SecurityName(wifi.SecurityFromMac(4))
    println wifi.SecurityName(wifi.SecurityFromMac(11))
    println wifi.SecurityName(wifi.SecurityFromMac(0))
    s := wifi.Security.Owe
    owe := wifi.Status { security = s }
    println wifi.SecurityName(s), owe.IsInsecure()
    println wifi.SignalFromDbm(-45), wifi.SignalFromDbm(-80), wifi.SignalFromDbm(0)
end
Outputwpa2 wpa3 enterprise open wpa2 wpa3 open wpa2 wpa3 open owe true 100 40 -1

Trust

enum Trust
The answer of Classify: NotWifi, Unknown, Trusted or Untrusted.
NameTypeDescription
NotWifiThe machine is not connected to Wi-Fi.
UnknownConnected and no trusted entry matches, but the system did not say which network it is and its security does not settle it. Also the answer when the state itself is unknown.
TrustedA trusted entry matches the network name or the access point, whatever the security of the network.
UntrustedNo trusted entry matches, and the network name is known, or the network is open, OWE or WEP.
net-wifi-Trust.salam
import net.wifi

func main:
    mut trusted := Vector {} as Vector<str>
    defer trusted.Free()
    trusted.Push("Home")
    trusted.Push("de:ad:be:ef:00:01")
    home := wifi.Status {
        state = wifi.State.Connected,
        ssid = "Home",
        ssid_known = true,
        security = wifi.Security.Wpa2
    }
    cafe := wifi.Status {
        state = wifi.State.Connected,
        ssid = "Cafe",
        ssid_known = true,
        security = wifi.Security.Wpa2
    }
    hidden := wifi.Status {
        state = wifi.State.Connected,
        security = wifi.Security.Wpa3,
        reason = "the system withheld the SSID"
    }
    hidden_open := wifi.Status { state = wifi.State.Connected, security = wifi.Security.Open }
    known_ap := wifi.Status { state = wifi.State.Connected, bssid = "DE:AD:BE:EF:00:01" }
    wired := wifi.Status { state = wifi.State.Disconnected }
    each s in [home, cafe, hidden, hidden_open, known_ap, wired]:
        t := wifi.Classify(s, trusted)
        println wifi.TrustName(t), wifi.IsUntrusted(s, trusted), t == wifi.Trust.Unknown
    end
end
Outputtrusted false false untrusted true false unknown false true untrusted true false trusted false false not-wifi false false

Status

struct Status
One wireless interface and the network it is on.
NameTypeDescription
stateStateWhether the interface is connected.
interfacestr = ""The interface name, such as wlan0 or en0, or the adapter description on Windows.
ssidstr = ""The network name. Only meaningful when ssid_known is true; empty otherwise.
ssid_knownbool = falseTrue when the system reported a usable network name. False on a hidden network, when the system needs a permission first, or when the name contains a NUL byte.
bssidstr = ""The access point address in lowercase, aa:bb:cc:dd:ee:ff, or empty.
securitySecurityHow the network is protected.
signalint = -1The signal quality from 0 to 100, or -1 when unknown.
backendstr = ""Where the answer came from: networkmanager, iw, sysfs, wlanapi, corewlan, none or unsupported.
reasonstr = ""Why something is missing, for example why the network name is not known. Empty when nothing is.
net-wifi-Current.salam
import net.wifi

func main:
    if not wifi.Supported():
        println "no Wi-Fi backend on this platform"
        ret
    end
    s := wifi.Current()
    println "state:", wifi.StateName(s.state)
    println "interface:", s.interface
    if s.ssid_known:
        println "network:", s.ssid
    else:
        println "network name hidden:", s.reason
    end
    println "access point:", s.bssid
    println "security:", wifi.SecurityName(s.security), "insecure:", s.IsInsecure()
    println "signal:", s.signal, "backend:", s.backend, "connected:", s.IsConnected()
    wifi.FreeStatus(s)
end

IsConnected

func IsConnected(): bool
True when the state is Connected.

The example for this item is shown with the ones above: net-wifi-State.salam

IsInsecure

func IsInsecure(): bool
True when anyone can join the network: Open, Owe or Wep.

The example for this item is shown with the ones above: net-wifi-Security.salam

Functions

StateName

func StateName(s: State): str
The name of a state: unknown, no-wifi, disconnected or connected.

The example for this item is shown with the ones above: net-wifi-State.salam

SecurityName

func SecurityName(s: Security): str
The name of a security mode: unknown, open, owe, wep, wpa, wpa2, wpa3 or enterprise.

The example for this item is shown with the ones above: net-wifi-Security.salam

TrustName

func TrustName(t: Trust): str
The name of a trust answer: not-wifi, unknown, trusted or untrusted.

The example for this item is shown with the ones above: net-wifi-State.salam

SignalFromDbm

func SignalFromDbm(dbm: int): int
Turns a signal level in dBm into 0 to 100 (-50 dBm and above is 100, -100 dBm and below is 0). Values of 0 or more mean unknown and give -1.

The example for this item is shown with the ones above: net-wifi-Security.salam

SecurityFromNm

func SecurityFromNm(flags: int, wpa: int, rsn: int): Security
Maps the Flags, WpaFlags and RsnFlags of a NetworkManager access point to a security mode.

The example for this item is shown with the ones above: net-wifi-Security.salam

SecurityFromWlan

func SecurityFromWlan(auth: int, cipher: int, onex: bool): Security
Maps a Windows DOT11_AUTH_ALGORITHM and DOT11_CIPHER_ALGORITHM, and whether 802.1X is on, to a security mode.

The example for this item is shown with the ones above: net-wifi-Security.salam

SecurityFromMac

func SecurityFromMac(code: int): Security
Maps a CoreWLAN CWSecurity value to a security mode.

The example for this item is shown with the ones above: net-wifi-Security.salam

DecodeSsid

func DecodeSsid(text: str): str
Turns the \xNN escapes that iw prints for bytes outside plain ASCII back into the bytes of the name. A name with a NUL byte gives an empty result.
net-wifi-Parsers.salam
import net.wifi

func main:
    names := wifi.ParseIwDev("phy#0\n\tInterface wlan0\n\t\ttype managed\n")
    println names.Len(), names[0]
    names.Free()
    link := wifi.ParseIwLink(
        "Connected to aa:bb:cc:dd:ee:ff (on wlan0)\n\tSSID: Sal\\xc3\\xa1m\n\tsignal: -58 dBm\n",
        "wlan0"
    )
    println wifi.StateName(link.state), link.ssid, link.bssid, link.signal
    scan := "BSS aa:bb:cc:dd:ee:ff(on wlan0) -- associated\n\tcapability: ESS Privacy (0x0411)\n\tRSN:\t * Version: 1\n\t\t * Authentication suites: PSK\n"
    println wifi.SecurityName(wifi.ParseIwScan(scan, link.bssid))
    println wifi.DecodeSsid("Office\\x20Guest")
end
Output1 wlan0 connected Salám aa:bb:cc:dd:ee:ff 84 wpa2 Office Guest

ParseIwDev

func ParseIwDev(text: str): Vector<str>
The interface names in the output of iw dev.

The example for this item is shown with the ones above: net-wifi-Parsers.salam

func ParseIwLink(text: str, iface: str): Status
Reads the output of iw dev NAME link into a Status for that interface. Release it with FreeStatus.

The example for this item is shown with the ones above: net-wifi-Parsers.salam

ParseIwScan

func ParseIwScan(text: str, bssid: str): Security
Finds the access point with the given address in the output of iw dev NAME scan dump and returns its security.

The example for this item is shown with the ones above: net-wifi-Parsers.salam

ParseWlanConnection

func ParseWlanConnection(p: void*, n: int): Status
Reads a WLAN_CONNECTION_ATTRIBUTES buffer from WlanQueryInterface into a Status. Release it with FreeStatus.
net-wifi-Windows.salam
import mem
import net.wifi

func put32(p: void*, off: int, v: int):
    ((p as i64 + off as i64) as u32*)[0] = v as u32
end

func main:
    buf := mem.AllocateZeroed(604 as u64)
    defer mem.Free(buf)
    put32(buf, 0, 1)
    put32(buf, 520, 2)
    ((buf as i64 + 524 as i64) as u8*)[0] = 72 as u8
    ((buf as i64 + 525 as i64) as u8*)[0] = 105 as u8
    put32(buf, 576, 80)
    put32(buf, 588, 1)
    put32(buf, 596, 7)
    put32(buf, 600, 4)
    s := wifi.ParseWlanConnection(buf, 604)
    println wifi.StateName(s.state),
        s.ssid,
        s.ssid_known,
        wifi.SecurityName(s.security),
        s.signal,
        s.backend
end
Outputconnected Hi true wpa2 80 wlanapi

Supported

func Supported(): bool
True when this platform has a Wi-Fi backend: Linux, Windows and macOS.

The example for this item is shown with the ones above: net-wifi-Current.salam

Interfaces

func Interfaces(): Vector<Status>
Every wireless interface the backend reports. A backend that fails (for example WlanOpenHandle on Windows) gives one entry with state Unknown and the cause in reason. Release the list with FreeStatuses.
net-wifi-Interfaces.salam
import net.wifi

func main:
    all := wifi.Interfaces()
    defer wifi.FreeStatuses(all)
    if all.Len() == 0:
        println "no wireless interface"
    end
    each s in all:
        println s.interface, wifi.StateName(s.state), s.ssid, wifi.SecurityName(s.security)
    end
end

Current

func Current(): Status
The connected interface, or else a disconnected one, or else an interface whose state is Unknown; a Status with state NoWifi only when there is no wireless interface. Never fails. Release the result with FreeStatus.

The example for this item is shown with the ones above: net-wifi-Current.salam

BestIndex

func BestIndex(list: Vector<Status>): int
The position of the entry Current would choose from a list: the first connected one, else the first disconnected one, else 0; -1 for an empty list. Pure, so it can be tested with Status values you build yourself.

The example for this item is shown with the ones above: net-wifi-Current.salam

FreeStatus

func FreeStatus(s: Status)
Releases the interface, ssid and bssid text of a Status that Current, ParseIwLink or ParseWlanConnection returned. Do not use the Status afterwards, and never pass one you built yourself.

The example for this item is shown with the ones above: net-wifi-Current.salam

FreeStatuses

func FreeStatuses(list: Vector<Status>)
Releases every Status in a list from Interfaces, then the list itself.

The example for this item is shown with the ones above: net-wifi-Interfaces.salam

Changed

func Changed(a: Status, b: Status): bool
True when two results name a different interface, network, access point, security or state. The signal is ignored.
net-wifi-Watch.salam
import net.wifi
import sync

func main:
    mut trusted := Vector {} as Vector<str>
    defer trusted.Free()
    trusted.Push("Home")
    mut last := wifi.Current()
    repeat 3:
        now := wifi.Current()
        if wifi.Changed(last, now):
            println "network changed to", now.ssid
            if wifi.IsUntrusted(now, trusted):
                println "untrusted Wi-Fi: connect the VPN"
            end
            wifi.FreeStatus(last)
            last = now
        else:
            wifi.FreeStatus(now)
        end
        sync.SleepMs(1000)
    end
    wifi.FreeStatus(last)
end

Classify

func Classify(s: Status, trusted: Vector<str>): Trust
Decides whether a status is a trusted network. An entry shaped like aa:bb:cc:dd:ee:ff matches only the BSSID, without case; any other entry matches only the network name, exactly. A match wins over everything, even an open network. When no entry matches: a known name is Untrusted, an open, OWE or WEP network is Untrusted, and anything else is Unknown.

The example for this item is shown with the ones above: net-wifi-Trust.salam

IsUntrusted

func IsUntrusted(s: Status, trusted: Vector<str>): bool
True when Classify answers Untrusted. Unknown and NotWifi are false.

The example for this item is shown with the ones above: net-wifi-Trust.salam