Skip to main content

Detecting Available Network Interfaces

How To Check Which Interfaces Are Available For Use

A device’s imp may have access to multiple network interfaces. Any application which makes use of these interfaces — for example, for local networking (impOS 42 and up) — will find it useful to be able to determine which of these interfaces are available for use.

The following code provides a means to do this. It uses the imp API method imp.net.info() to get a list of the network interfaces attached to the device via its host imp. For each of these interfaces, the code creates an app-level record and stores in the table variable interfaces. The record includes the interface’s type, a boolean value to indicate whether it is available for use, and the interface object used to access the interface via impOS.

For each known interface, the code calls imp.net.open() to set the interface up for local networking. If this succeeds, and the interface connects to a network, the code notes its availability for such usage and then closes the connection by setting the referrer variable to null.

How do we know the connection succeeded? imp.net.open() registers a callback function to which interface state change notifications are sent when they are detected by impOS. The code within the callback examines the reported state and marks the interface as available upon connection. If the interface subsequently reports a problem, the code marks the interface as unavailable.

It is possible to connect multiple interfaces of the same type to an imp module, so the callback registration uses Squirrel’s bindenv() function to bind the callback to the relevant interface record which thus becomes accessible to the callback code through the context variable this. We do this because the state-change callback of itself has no information to indicate which interface triggered its execution. As an alternative approach, we could have registered a number of interface-specific callbacks, but this increases the length of the code and requires the application to ‘know’ which interfaces will be wired to the imp. The code below does not need this information.

The key code is included in the function getAvailableInterfaces(), but the sample below also includes a function, reportInterfaces(), to log the results. A real-world app would not necessarily include this, or the variables interfaceCount and reportCount, which are used to determine when all the checks have been performed. Application code can use the variables isWifiAvailable, isEthernetAvailable and isCellularAvailable, which are available throughout the app's runtime, to determine whether a given network type is available for use.

Code

API Methods Used

Further Reading