Flutter/Dart: Scan local network to get IP and hostname of connected devices
OK, I got it working and want to share my solution.
I used the network_info_plus package and the dart:io package.
import 'dart:io';
import 'package:network_info_plus/network_info_plus.dart';
Future<void> scanNetwork() async {
await (NetworkInfo().getWifiIP()).then(
(ip) async {
final String subnet = ip!.substring(0, ip.lastIndexOf('.'));
const port = 22;
for (var i = 0; i < 256; i++) {
String ip = '$subnet.$i';
await Socket.connect(ip, port, timeout: Duration(milliseconds: 50))
.then((socket) async {
await InternetAddress(socket.address.address)
.reverse()
.then((value) {
print(value.host);
print(socket.address.address);
}).catchError((error) {
print(socket.address.address);
print('Error: $error');
});
socket.destroy();
}).catchError((error) => null);
}
},
);
print('Done');
}
I'm "scanning" the local network by trying to connect to a given ip and port. If that works, I found a device, I'm looking for. In that cause I also try to get the hostname by using the "reverse()" method.
I have tested it on several iOS and Android devices and it works fine with no errors, so I think its a proper solution.
Aterus
Updated on December 30, 2022Comments
-
Aterus over 1 year
I'm working on a mobile app using Flutter and want to scan the local network for connected devices. I found the ping_discover_network package, which is working fine, but only gets me the IP address, but I also want to show the hostname of the device.
I tried the reverse() method of the InternetAddress class from the dart:io package, but this only gets me the IP address back. Example:
InternetAddress(ip).reverse().then((value) => print(value));
Is there another package or something I can use, to scan the local network of the app and get the IP address and the hostname back?