kaluma-project / kaluma

A tiny JavaScript runtime for RP2040 (Raspberry Pi Pico)
https://kalumajs.org
Apache License 2.0
648 stars 37 forks source link

how to get IP address #637

Open pankleks opened 9 months ago

pankleks commented 9 months ago

Hello,

How to get IP address after wifi is connected?

I was looking through docs but could not found it.

Thank you

communix commented 8 months ago

IP address is network address. So you need to connect to the network. You can see the local IP address in the net module, Socket class.

https://kalumajs.org/docs/api/net#socketlocaladdress

krish-ag commented 8 months ago

Collaborator

I tried as u asked, but I get undefined as output.

image

image

pankleks commented 8 months ago

you need to put checking code after Connected to Wi-fi... else it's called immediatelly - not after wifi is really connected.

tricoos commented 8 months ago

Still doesn't work, why is there no such function? This is such an essential functionality and should be part of the connection info:

const WiFi = require('wifi').WiFi,
    net = require('net'),
    wifi = new WiFi();

console.log("Connecting to WiFi....");
wifi.connect((err) => {
    if (err) {
        console.error(err);
    } else {
        wifi.getConnection((err, connInfo) => {
            console.log("Connected to Wifi: "+connInfo.ssid);
            const sock = new net.Socket();
            console.log('Address:', sock.localAddress);
        });
    }
});
Connecting to WiFi....
Connected to Wifi: MyWifi
Address: null
tricoos commented 8 months ago

With some issue digging I found this: https://github.com/kaluma-project/kaluma/issues/554

That lead me to this code:

console.log("Connecting to WiFi....");
wifi.connect((err) => {
    if (err) {
        console.error(err);
    } else {
        wifi.getConnection((err, connInfo) => {
            console.log("Connected to Wifi: "+connInfo.ssid);
            console.log('Creating HTTP server simply to get my IP...');
            const server = http.createServer();
            server.listen(80, () => {
                console.log(`Yay, my IP is ${server._dev.ip}`);
                console.log('Shutting down server...');
                server.close();
                console.log('On with my code....');
            });
        });
    }
});

Is this really the only way? Spinning up an HTTP server simply to get the local IP address? Even in LUA for ESP8266 something like this has been available forever: https://nodemcu.readthedocs.io/en/release/modules/wifi/#wifistagetip