I'm using the following code to retrieve the client IP in my electron application:
const fnOSIP = () => {
const nets = networkInterfaces();
const results = Object.create(null); // or just '{}', an empty object
for (const name of Object.keys(nets)) {
for (const net of nets[name]) {
// skip over non-ipv4 and internal (i.e. 127.0.0.1) addresses
if (net.family === 'IPv4' && !net.internal) {
if (!results[name]) {
results[name] = [];
}
results[name].push(net.address);
}
}
}
return results;
}
The problem is that it's returning two IP's. I would like to get the primary but not quite sure.
If I do a command: ip address I can get the following information of each IP:
3: wlp0s20f3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1000
link/ether 08:d2:3e:a5:46:37 brd ff:ff:ff:ff:ff:ff
inet 192.168.0.117/24 brd 192.168.0.255 scope global dynamic noprefixroute wlp0s20f3
valid_lft 4944sec preferred_lft 4944sec
inet6 fe80::7701:3d92:db95:9fdc/64 scope link noprefixroute
valid_lft forever preferred_lft forever
16: br-f5f2e5a5a382: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
link/ether 02:42:23:09:cb:c9 brd ff:ff:ff:ff:ff:ff
inet 172.19.0.1/16 brd 172.19.255.255 scope global br-f5f2e5a5a382
valid_lft forever preferred_lft forever
inet6 fe80::42:23ff:fe09:cbc9/64 scope link
valid_lft forever preferred_lft forever
The br-f5f2...
is from docker:
Would it make sense to assume that if it has /24 it's the primary?
The Problem is, you have to strip the internal Addresses. I use this script to terieve the IP of a Client:
function getIPs() {
var ifaces = os.networkInterfaces();
let ipAdresse = {};
Object.keys(ifaces).forEach(function (ifname) {
let alias = 0;
ifaces[ifname].forEach(function (iface) {
if ('IPv4' !== iface.family || iface.internal !== false) {
// skip over internal (i.e. 127.0.0.1) and non-ipv4 addresses
return;
}
if (alias >= 1) {
// this single interface has multiple ipv4 addresses
console.log(ifname + ':' + alias, iface.address);
} else {
// this interface has only one ipv4 adress
console.log(ifname, iface.address);
ipAdresse = {IP: iface.address, MAC: iface.mac};
}
++alias;
});
});
return ipAdresse;
}
The Problem (and I could not find a solution for that) is, if the machine has two interfaces (like LAN and WIFI enabled at the same time) you cannot determine which is which.