Skip to content

Commit

Permalink
Merge pull request #189 from osociety/dev
Browse files Browse the repository at this point in the history
Dev -> Main
  • Loading branch information
git-elliot authored Mar 17, 2024
2 parents 24b263a + 009ce7a commit 84c9068
Show file tree
Hide file tree
Showing 16 changed files with 58 additions and 45 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# Change Log

## 5.0.1
1. Bug fixes and improvements

## 5.0.0
1. Added hostIds list parameter to restrict scan to only these ids.
2. Breaking changes on calling static methods. You have to use instance of service now.
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ Future<void> main() async {
```dart
//1. Range
String target = '192.168.1.1';
PortScanner.scanPortsForSingleDevice(target, startPort: 1, endPort: 1024,
PortScannerService.instance.scanPortsForSingleDevice(target, startPort: 1, endPort: 1024,
progressCallback: (progress) {
print('Progress for port discovery : $progress');
}).listen((ActiveHost event) {
Expand All @@ -99,7 +99,7 @@ Future<void> main() async {
### Mdns Scanner

```dart
for (final ActiveHost activeHost in await MdnsScanner.searchMdnsDevices()) {
for (final ActiveHost activeHost in await MdnsScannerService.instance.searchMdnsDevices()) {
final MdnsInfo? mdnsInfo = await activeHost.mdnsInfo;
print('''
Address: ${activeHost.address}
Expand Down
4 changes: 2 additions & 2 deletions example/lib/example_utils.dart
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import 'package:logging/logging.dart';

final examplesLog = Logger("network_tools_examples");
final examplesLogger = Logger("network_tools_examples");

void enableExampleLogging() {
Logger.root.level = Level.FINE;
Logger.root.onRecord.listen((record) {
if (record.loggerName == examplesLog.name) {
if (record.loggerName == examplesLogger.name) {
// ignore: avoid_print
print(
'${record.time.toLocal()}: ${record.level.name}: ${record.loggerName}: ${record.message}',
Expand Down
8 changes: 4 additions & 4 deletions example/lib/scan/host_scan.dart
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ Future<void> main() async {

// or You can also get address using network_info_plus package
// final String? address = await (NetworkInfo().getWifiIP());
examplesLog.fine("Starting scan on subnet $subnet");
examplesLogger.fine("Starting scan on subnet $subnet");

// You can set [firstHostId] and scan will start from this host in the network.
// Similarly set [lastHostId] and scan will end at this host in the network.
Expand All @@ -25,18 +25,18 @@ Future<void> main() async {
// firstHostId: 1,
// lastHostId: 254,
progressCallback: (progress) {
examplesLog.finer('Progress for host discovery : $progress');
examplesLogger.finer('Progress for host discovery : $progress');
},
);

stream.listen(
(host) async {
//Same host can be emitted multiple times
//Use Set<ActiveHost> instead of List<ActiveHost>
examplesLog.fine('Found device: ${await host.toStringFull()}');
examplesLogger.fine('Found device: ${await host.toStringFull()}');
},
onDone: () {
examplesLog.fine('Scan completed');
examplesLogger.fine('Scan completed');
},
); // Don't forget to cancel the stream when not in use.
}
2 changes: 1 addition & 1 deletion example/lib/scan/mdns_scan.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ Future<void> main() async {
for (final ActiveHost activeHost
in await MdnsScannerService.instance.searchMdnsDevices()) {
final MdnsInfo? mdnsInfo = await activeHost.mdnsInfo;
examplesLog.fine(
examplesLogger.fine(
'Address: ${activeHost.address}, Port: ${mdnsInfo!.mdnsPort}, ServiceType: ${mdnsInfo.mdnsServiceType}, MdnsName: ${mdnsInfo.getOnlyTheStartOfMdnsName()}, Mdns Device Name: ${mdnsInfo.mdnsSrvTarget}\n',
);
}
Expand Down
18 changes: 9 additions & 9 deletions example/lib/scan/port_scan.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ Future<void> main() async {
final netId = interface?.networkId;
if (netId != null) {
subnet = netId;
examplesLog.fine('subnet id $subnet');
examplesLogger.fine('subnet id $subnet');
}

// [New] Scan for a single open port in a subnet
Expand All @@ -22,31 +22,31 @@ Future<void> main() async {
subnet,
53,
progressCallback: (progress) {
examplesLog.finer('Progress for port discovery on host : $progress');
examplesLogger.finer('Progress for port discovery on host : $progress');
},
);

stream2.listen(
(ActiveHost activeHost) {
examplesLog
examplesLogger
.fine('[scanDevicesForSinglePort]: Found device : $activeHost');
final OpenPort deviceWithOpenPort = activeHost.openPorts[0];
if (deviceWithOpenPort.isOpen) {
examplesLog.fine(
examplesLogger.fine(
'[scanDevicesForSinglePort]: Found open port: ${deviceWithOpenPort.port} on ${activeHost.address}',
);
}
},
onDone: () {
examplesLog.fine('Port Scan completed');
examplesLogger.fine('Port Scan completed');
},
); // Don't forget to cancel the stream when not in use.

String target = '192.168.1.1';
final addr = interface?.ipAddress;
if (addr != null) {
target = addr;
examplesLog.fine("Target is $target");
examplesLogger.fine("Target is $target");
}

PortScannerService.instance.scanPortsForSingleDevice(
Expand All @@ -55,20 +55,20 @@ Future<void> main() async {
// startPort: 1,
endPort: 9400,
progressCallback: (progress) {
examplesLog.finer('Progress for port discovery : $progress');
examplesLogger.finer('Progress for port discovery : $progress');
},
).listen(
(activeHost) {
final OpenPort deviceWithOpenPort = activeHost.openPorts[0];

if (deviceWithOpenPort.isOpen) {
examplesLog.fine(
examplesLogger.fine(
'Found open port: ${deviceWithOpenPort.port} on device $target',
);
}
},
onDone: () {
examplesLog.fine('Port Scan from 1 to 9400 completed');
examplesLogger.fine('Port Scan from 1 to 9400 completed');
},
);
}
12 changes: 6 additions & 6 deletions lib/src/configure_dart_native.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import 'package:logging/logging.dart';
import 'package:network_tools/network_tools.dart' as pacakges_page;
import 'package:network_tools/network_tools.dart' as packages_page;
import 'package:network_tools/src/network_tools_utils.dart';
import 'package:network_tools/src/services/arp_service.dart';
import 'package:network_tools/src/services/impls/arp_service_sembast_impl.dart';
Expand All @@ -11,13 +11,13 @@ Future<void> configureNetworkTools(
String dbDirectory, {
bool enableDebugging = false,
}) async {
pacakges_page.enableDebugging = enableDebugging;
pacakges_page.dbDirectory = dbDirectory;
packages_page.enableDebugging = enableDebugging;
packages_page.dbDirectory = dbDirectory;

if (pacakges_page.enableDebugging) {
if (packages_page.enableDebugging) {
Logger.root.level = Level.FINE;
Logger.root.onRecord.listen((record) {
if (record.loggerName == log.name) {
if (record.loggerName == logger.name) {
// ignore: avoid_print
print(
'${record.time.toLocal()}: ${record.level.name}: ${record.loggerName}: ${record.message}',
Expand All @@ -34,5 +34,5 @@ Future<void> configureNetworkTools(

final arpService = await ARPService.instance.open();
await arpService.buildTable();
await pacakges_page.VendorTable.createVendorTableMap();
await packages_page.VendorTable.createVendorTableMap();
}
9 changes: 9 additions & 0 deletions lib/src/device_info/arp_table_helper.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,20 @@ import 'package:logging/logging.dart';
import 'package:network_tools/src/models/arp_data.dart';
import 'package:universal_io/io.dart';

/// Retreiving ARP packets is only supported for Desktop such as
/// Linux, Windows, and macOS. Dart native doesn't provide a way or rejects
/// call to arp command on mobile such as Android and iOS.
/// Maybe in future dart native will support sending raw packets,
/// so that time we can add implementation for mobile devices.
/// Currenlty this is achieved by process package.
class ARPTableHelper {
static final arpLogger = Logger("arp-table-logger");

/// Fires arp -a command only on 3 platforms i.e., Linux, Windows, and macOS
/// and returns the result in form of ARPData after parsing each line.
static Future<List<ARPData>> buildTable() async {
final arpEntries = <ARPData>[];
// ARP is not allowed to be run for mobile devices currenlty.
if (Platform.isAndroid || Platform.isIOS) return arpEntries;
final result = await Process.run('arp', ['-a']);
final entries = const LineSplitter().convert(result.stdout.toString());
Expand Down
6 changes: 3 additions & 3 deletions lib/src/device_info/vendor_table.dart
Original file line number Diff line number Diff line change
Expand Up @@ -38,17 +38,17 @@ class VendorTable {
final csvPath = p.join(dbDirectory, "mac-vendors-export.csv");
final file = File(csvPath);
if (!await file.exists()) {
log.fine("Downloading mac-vendors-export.csv from network_tools");
logger.fine("Downloading mac-vendors-export.csv from network_tools");
final response = await http.get(
Uri.https(
"raw.githubusercontent.com",
"osociety/network_tools/main/lib/assets/mac-vendors-export.csv",
),
);
file.writeAsBytesSync(response.bodyBytes);
log.fine("Downloaded mac-vendors-export.csv successfully");
logger.fine("Downloaded mac-vendors-export.csv successfully");
} else {
log.fine("File mac-vendors-export.csv already exists");
logger.fine("File mac-vendors-export.csv already exists");
}

final input = file.openRead();
Expand Down
10 changes: 5 additions & 5 deletions lib/src/mdns_scanner/get_srv_list_by_os/srv_list_linux.dart
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ class SrvListLinux {
srvList.addAll(await runAvahiBrowseCommand());
srvList.addAll(await runMdnsScanCommand());
} catch (e) {
log.severe('Error:\n$e');
logger.severe('Error:\n$e');
}
return srvList.toList();
}
Expand All @@ -35,7 +35,7 @@ timeout 2s avahi-browse --all -p
final String? resultStderr = error.result?.stderr.toString();
if (resultStderr != null &&
resultStderr.contains('No such file or directory')) {
log.fine(
logger.fine(
'You can make the mdns process better by installing `avahi-browse`',
);
return [];
Expand All @@ -59,7 +59,7 @@ timeout 2s avahi-browse --all -p
}
}
} catch (e) {
log.severe('Error getting info from avahi-browse\n$e');
logger.severe('Error getting info from avahi-browse\n$e');
}
return srvListAvahi;
}
Expand All @@ -84,7 +84,7 @@ timeout 2s mdns-scan

if (resultStderr == null ||
(resultStderr.contains('No such file or directory'))) {
log.fine(
logger.fine(
'You can make the mdns process better by installing `mdns-scan`',
);
return [];
Expand All @@ -105,7 +105,7 @@ timeout 2s mdns-scan
}
}
} catch (e) {
log.severe('Error getting info from mdns-scan\n$e');
logger.severe('Error getting info from mdns-scan\n$e');
}
return srvListMdnsScan;
}
Expand Down
2 changes: 1 addition & 1 deletion lib/src/models/active_host.dart
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ class ActiveHost {
// throw exception.
// We don't need to print this crash as it is by design.
} else {
log.severe('Exception here: $e');
logger.severe('Exception here: $e');
}
}
return null;
Expand Down
2 changes: 1 addition & 1 deletion lib/src/network_tools_utils.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import 'package:logging/logging.dart';

final log = Logger("network_tools");
final logger = Logger("network_tools");
15 changes: 8 additions & 7 deletions lib/src/services/impls/host_scanner_service_impl.dart
Original file line number Diff line number Diff line change
Expand Up @@ -115,11 +115,11 @@ class HostScannerServiceImpl extends HostScannerService {
if (pingError == null) {
final Duration? time = response.time;
if (time != null) {
log.fine("Pingable device found: $host");
logger.fine("Pingable device found: $host");
tempSendableActivateHost =
SendableActiveHost(host, pingData: pingData);
} else {
log.fine("Non pingable device found: $host");
logger.fine("Non pingable device found: $host");
}
}
}
Expand All @@ -128,16 +128,16 @@ class HostScannerServiceImpl extends HostScannerService {
final data = await (await arpServiceFuture).entryFor(host);

if (data != null) {
log.fine("Successfully fetched arp entry for $host as $data");
logger.fine("Successfully fetched arp entry for $host as $data");
tempSendableActivateHost =
SendableActiveHost(host, pingData: pingData);
} else {
log.fine("Problem in fetching arp entry for $host");
logger.fine("Problem in fetching arp entry for $host");
}
}

if (tempSendableActivateHost != null) {
log.fine("Successfully added to result $host");
logger.fine("Successfully added to result $host");
activeHostsController.add(tempSendableActivateHost);
}
}
Expand Down Expand Up @@ -181,7 +181,7 @@ class HostScannerServiceImpl extends HostScannerService {
i <= lastValidSubnet;
i += scanRangeForIsolate + 1) {
final limit = min(i + scanRangeForIsolate, lastValidSubnet);
log.fine('Scanning from $i to $limit');
logger.fine('Scanning from $i to $limit');

final receivePort = ReceivePort();
final isolate =
Expand Down Expand Up @@ -232,7 +232,8 @@ class HostScannerServiceImpl extends HostScannerService {
final bool resultsInAddressAscendingOrder = message[4] == "true";
final String dbDirectory = message[5];
final bool enableDebugging = message[6] == "true";
final List<int> hostIds = message[7]
final String joinedIds = message[7];
final List<int> hostIds = joinedIds
.split(',')
.where((e) => e.isNotEmpty)
.map(int.parse)
Expand Down
2 changes: 1 addition & 1 deletion lib/src/services/impls/mdns_scanner_service_impl.dart
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ class MdnsScannerServiceImpl extends MdnsScannerService {
listOfActiveHost.add(activeHost);
}
} catch (e) {
log.severe(
logger.severe(
'Error finding ip of mdns record ${ptr.name} srv target ${srv.target}, will add it with ip 0.0.0.0\n$e',
);
final ActiveHost activeHost = convertSrvToHostName(
Expand Down
2 changes: 1 addition & 1 deletion pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name: network_tools
description: Networking Tools library which can help you discover open ports, devices on subnet and many other things.
version: 5.0.0
version: 5.0.1
issue_tracker: https://github.com/osociety/network_tools/issues
repository: https://github.com/osociety/network_tools

Expand Down
4 changes: 2 additions & 2 deletions test/network_tools_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ void main() {
server =
await ServerSocket.bind(InternetAddress.anyIPv4, port, shared: true);
port = server.port;
log.fine("Opened port in this machine at $port");
logger.fine("Opened port in this machine at $port");

final interface = await NetInterface.localInterface();
if (interface != null) {
Expand All @@ -44,7 +44,7 @@ void main() {
}
}
}
log.fine(
logger.fine(
'Fetched own host as $myOwnHost and interface address as $interfaceIp',
);
}
Expand Down

0 comments on commit 84c9068

Please sign in to comment.