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 IP address is, such as, 192.168.x.xxx and NOT the public IP address of the router.

So far, I can only seem to find InternetAddress.anyIPv4 and InternetAddress.loopbackIPv4. The loopback address is not what I want as it is 127.0.0.1.

解决方案

I guess you mean the local IP of the currently connected Wifi network, right?

EDIT: NetworkInterface.list is not supported in Android, as later pointed out by Mahesh. Aside from the wifi package suggested in his answer, there's a PR to bring that to the connectivity plugin.

You may also want to check if Wifi is available using the connectivity plugin in flutter/plugins.

Right below there's a simple example of usage of NetworkInferface. By the way, here's an example of how to check if wifi is available.

import 'dart:io';

import 'package:flutter/material.dart';

main() {

runApp(new MyApp());

}

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return new MaterialApp(

title: "Network Interface example",

home: new NetworkInterfaceWidget(),

);

}

}

class NetworkInterfaceWidget extends StatefulWidget {

@override

_NetworkInterfaceState createState() => new _NetworkInterfaceState();

}

class _NetworkInterfaceState extends State {

String _networkInterface;

@override

initState() {

super.initState();

NetworkInterface.list(includeLoopback: false, type: InternetAddressType.any)

.then((List interfaces) {

setState( () {

_networkInterface = "";

interfaces.forEach((interface) {

_networkInterface += "### name: ${interface.name}\n";

int i = 0;

interface.addresses.forEach((address) {

_networkInterface += "${i++}) ${address.address}\n";

});

});

});

});

}

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(

title: Text("NetworkInterface"),

),

body: Container(

padding: EdgeInsets.all(10.0),

child: Text("Only in iOS.. :(\n\nNetworkInterface:\n $_networkInterface"),

),

);

}

}

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐