Archive
Enumerating network adapters in DWScript/Smart under Node.js
This is something I never had the time to implement under Smart Pascal, but it should be easy enough to patch. If you are using DWScript with the QTX Framework this is already in place. But for Smart users, here is a quick recipe.
First, we need access to the node.js OS module:
unit qtx.node.os; //############################################################################# // Quartex RTL for DWScript // Written by Jon L. Aasenden, all rights reserved // This code is released under modified LGPL (see license.txt) //############################################################################# unit NodeJS.os; interface uses NodeJS.Core; type TCpusResultObjectTimes = class external property user: Integer; property nice: Integer; property sys: Integer; property idle: Integer; property irq: Integer; end; TCpusResult = class external property model: String; property speed: Integer; property times: TcpusResultObjectTimes; end; JNetworkInterfaceInfo = class external property address: string; property netmask: string; property family: string; property mac: string; property scopeid: integer; property internal: boolean; property cidr: string; end; Jos_Exports = class external public function tmpDir: String; function hostname: String; function &type: String; function platform: String; function arch: String; function release: String; function uptime: Integer; function loadavg: array of Integer; function totalmem: Integer; function freemem: Integer; function cpus: array of TCpusResult; function networkInterfaces: variant; property EOL: String; end; function NodeJSOsAPI: Jos_Exports; implementation function NodeJSOsAPI: Jos_Exports; begin result := Jos_Exports(RequireModule("os") ); end; end.
With that in place, we can start enumerating through the adapters. Remember that a PC can have several adapters attached, from a dedicated card to X number of USB wifi sticks.
Here is a little routine that goes through the adapters, and returns the first IPv4 LAN address it finds. This is very useful when writing servers, since you need the IP + port to setup a binding. And yes, you can just call HostName(), but the point here is to know how to run through the adapter array.
function GetMyV4LanIP: string; begin var OSAPI := NodeJSOsAPI(); var NetAdapters := OSAPI.networkInterfaces(); for var Adapter in NetAdapters do begin // Skip loopback device if Adapter.Contains('Loopback') then continue; for var netIntf in NetAdapters[Adapter] do begin var address = JNetworkInterfaceInfo( NetAdapters[Adapter][netIntf] ); if not address.internal then begin // force copy of string var lFam: string := string(address.family) + " "; // make sure its ipv4 if lFam.ToLower().Trim() = 'ipv4' then begin result := address.address + " "; result := result.trim(); break; end; end; end; end; if result.length < 1 then result := '127.0.0.1'; end;