Created
March 28, 2021 23:37
-
-
Save GuilhermeRossato/581e1e1a661dc223b72ba6680304bd7f to your computer and use it in GitHub Desktop.
Javascript (NodeJS) function to get the local IP from a network interface. (Uses windows default command line tool "ipconfig.exe" to get the local ip)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Warning: undefined behaviour if the network interface does not have an IP (might fail or might return the next interface ip) | |
| function getNetworkAdapterIp(adapter_name = "Adaptador de Rede sem Fio Wi-Fi", ip_version = 4, cp = require("child_process")) { | |
| process.stdout.setEncoding('utf-8'); | |
| /** @type {Buffer} */ | |
| const ipconfig_output = cp.spawnSync("C:\\Windows\\System32\\ipconfig.exe", ["/all"]).output[1]; | |
| const adapter_config = ipconfig_output.toString("utf-8").split(adapter_name + ":")[1]; | |
| if (!adapter_config) { | |
| return "ERROR - could not find adapter on output:\n" + (JSON.stringify(ipconfig_output.toString("utf-8"))); | |
| } else { | |
| const ip_config = adapter_config.split("IPv" + ip_version + ". . . . . . . . . . . . . . . :")[1]; | |
| if (!ip_config) { | |
| return "ERROR - could not find ipv" + ip_version + " from adapter string:\n" + (JSON.stringify(adapter_config)); | |
| } else { | |
| return (ip_config.split("\n")[0].split("(")[0].trim()); | |
| } | |
| } | |
| } | |
| // JSON.stringify(getNetworkAdapterIp()) === "192.168.0.16" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment