Search code examples
cordovaionic-frameworkcapacitorcapacitor-plugin

IONIC/CAPACITOR: Detecting device on local network


I am looking for a way to find an IP address of the TV connected to the same WIFI network as the phone so I can make some requests to it.

I am trying to build a remote control app for my TV (Sony Bravia) and I got the app running and working in the browser. Still, I would like to automate finding the IP address so I don't have to look for the IP manually, is there a way to do something like this with Ionic/Capacitor?


Solution

  • How I solved it, for the time being, is I used the Cordova plugin @awesome-cordova-plugins/network-interface to get the local IP address of the phone and then I looped over the rest of the network looking for a response

        const urls = (ip: string) => {
          const result = [];
          // we send in ip (192.168.1.1) then we remove last digit for search
          const prep_base_url = "http://" + ip.split(".").slice(0, -1).join(".") + ".";
          for (let i = 0; i < 255; i++) {
            result.push(prep_base_url + i + "/sony/system");
          }
          return result;
        };
        
        export const scanForTv = (ip: string) => {
          const result = Promise.allSettled(
            urls(ip).map((url) => getDeviceInfoUrl(url))
          ).then((data) => {
            return data.filter((x: any) => x.status === "fulfilled");
          });
          return result;
        };
    
    

    and that is how I find TV on the network.

    p.s. notice we are using HTTP and not HTTPS and that is not going to fly on android so just add this to your manifest so you don't waste too much time like me:

    <application
            android:usesCleartextTraffic="true">