How to get device IP in Dart/Flutter

前端 未结 8 814
孤城傲影
孤城傲影 2021-02-13 21:01

I am currently writing an app where the user needs to know the IP address of their phone/tablet. Where would I find this information?

I only want to know what the local

8条回答
  •  野性不改
    2021-02-13 21:51

    Here is another way.

     Future _retrieveIPAddress() async {
        InternetAddress result;
    
        int code = Random().nextInt(255);
        var dgSocket = await RawDatagramSocket.bind(InternetAddress.anyIPv4, 0);
        dgSocket.readEventsEnabled = true;
        dgSocket.broadcastEnabled = true;
        Future ret =
            dgSocket.timeout(Duration(milliseconds: 100), onTimeout: (sink) {
          sink.close();
        }).expand((event) {
          if (event == RawSocketEvent.read) {
            Datagram dg = dgSocket.receive();
            if (dg != null && dg.data.length == 1 && dg.data[0] == code) {
              dgSocket.close();
              return [dg.address];
            }
          }
          return [];
        }).firstWhere((InternetAddress a) => a != null);
    
        dgSocket.send([code], InternetAddress("255.255.255.255"), dgSocket.port);
        return ret;
      }
    

提交回复
热议问题