LCOV - code coverage report
Current view: top level - lib/src/device_info - arp_table_helper.dart (source / functions) Coverage Total Hit
Test: lcov.info Lines: 96.6 % 119 115
Test Date: 2026-11-15 16:52:47 Functions: - 0 0

            Line data    Source code
       1              : import 'dart:convert';
       2              : 
       3              : import 'package:logging/logging.dart';
       4              : import 'package:network_tools/src/models/arp_data.dart';
       5              : import 'package:universal_io/io.dart';
       6              : 
       7              : /// Retreiving ARP packets is only supported for Desktop such as
       8              : /// Linux, Windows, and macOS. Dart native doesn't provide a way or rejects
       9              : /// call to arp command on mobile such as Android and iOS.
      10              : /// Maybe in future dart native will support sending raw packets,
      11              : /// so that time we can add implementation for mobile devices.
      12              : /// Currenlty this is achieved by process package.
      13              : /// Helper class for retrieving and parsing the ARP table on supported desktop platforms.
      14              : class ARPTableHelper {
      15              :   /// [runArp] and [linuxArpPath] exist so the platform fallbacks can be tested
      16              :   /// on any machine; production code uses the defaults.
      17            7 :   ARPTableHelper({
      18              :     ProcessResult Function(List<String> arguments)? runArp,
      19              :     String linuxArpPath = '/proc/net/arp',
      20              :   }) : _runArp = runArp ?? _defaultRunArp,
      21              :        _linuxArpPath = linuxArpPath;
      22              : 
      23              :   final ProcessResult Function(List<String> arguments) _runArp;
      24              :   final String _linuxArpPath;
      25              : 
      26            1 :   static ProcessResult _defaultRunArp(List<String> arguments) =>
      27            1 :       Process.runSync('arp', arguments);
      28              : 
      29              :   /// Logger for ARP table operations.
      30           21 :   static final arpLogger = Logger("arp-table-logger");
      31              : 
      32              :   bool isMobilePlatform = Platform.isAndroid || Platform.isIOS;
      33              :   bool isMacOSPlatform = Platform.isMacOS;
      34              :   bool isLinuxPlatform = Platform.isLinux;
      35              : 
      36              :   /// Whether the ARP table can be read on this platform.
      37            2 :   bool get isARPSupported => !isMobilePlatform;
      38              : 
      39              :   /// How long the kernel is given to resolve neighbors after priming.
      40              :   static const Duration defaultPrimingDelay = Duration(milliseconds: 150);
      41              : 
      42            1 :   List<String> executeARPCommand() {
      43              :     // ARP is not allowed to be run for mobile devices currenlty.
      44            1 :     if (isMobilePlatform) {
      45            2 :       arpLogger.warning("ARP command is not supported on mobile platforms.");
      46            1 :       return [];
      47              :     }
      48              :     try {
      49            3 :       final result = _runArp(['-a']);
      50            2 :       if (result.exitCode != 0) {
      51            4 :         arpLogger.warning("Failed to execute ARP command: ${result.stderr}");
      52            1 :         return [];
      53              :       }
      54            3 :       return const LineSplitter().convert(result.stdout.toString());
      55            1 :     } on ProcessException catch (error) {
      56              :       // The arp binary can be missing on minimal systems (containers, some
      57              :       // Linux images). Host discovery still works, only MAC data is missing.
      58            3 :       arpLogger.warning("ARP command is unavailable: $error");
      59            1 :       return [];
      60              :     } catch (error, stackTrace) {
      61            2 :       arpLogger.warning(
      62            1 :         "Unexpected error while running ARP command: $error",
      63              :         error,
      64              :         stackTrace,
      65              :       );
      66            1 :       return [];
      67              :     }
      68              :   }
      69              : 
      70              :   /// Reads the ARP table without asking the OS to resolve host names.
      71              :   ///
      72              :   /// `arp -a` performs a reverse DNS lookup for every entry, which can block
      73              :   /// for seconds and frequently yields `?` anyway. Discovery only needs the
      74              :   /// address and MAC, so read the numeric form and resolve names separately
      75              :   /// for the hosts that were actually found.
      76            7 :   List<String> executeNumericARPCommand() {
      77            7 :     if (isMobilePlatform) {
      78            2 :       arpLogger.warning("ARP table is not available on mobile platforms.");
      79            1 :       return [];
      80              :     }
      81            7 :     if (isLinuxPlatform) {
      82            7 :       final procEntries = _readLinuxProcNetArp();
      83              :       if (procEntries != null) {
      84              :         return procEntries;
      85              :       }
      86              :     }
      87              :     try {
      88              :       // Keep the Linux fallback numeric too: `arp -a` performs a reverse
      89              :       // lookup per row, which is what this method exists to avoid. Windows
      90              :       // has no `-n` flag and prints numeric rows anyway.
      91            2 :       final arguments = (isMacOSPlatform || isLinuxPlatform)
      92              :           ? const <String>['-an']
      93              :           : const <String>['-a'];
      94            2 :       final result = _runArp(arguments);
      95            2 :       if (result.exitCode != 0) {
      96            4 :         arpLogger.warning("Failed to execute ARP command: ${result.stderr}");
      97            1 :         return [];
      98              :       }
      99            3 :       return const LineSplitter().convert(result.stdout.toString());
     100            1 :     } on ProcessException catch (error) {
     101              :       // The arp binary can be missing on minimal systems (containers, some
     102              :       // Linux images). Host discovery still works, only MAC data is missing.
     103            3 :       arpLogger.warning("ARP command is unavailable: $error");
     104            1 :       return [];
     105              :     } catch (error, stackTrace) {
     106            2 :       arpLogger.warning(
     107            1 :         "Unexpected error while running ARP command: $error",
     108              :         error,
     109              :         stackTrace,
     110              :       );
     111            1 :       return [];
     112              :     }
     113              :   }
     114              : 
     115              :   /// Linux exposes the neighbor table directly, avoiding both a process spawn
     116              :   /// and name resolution. Rows are converted to the `arp -a` line format so
     117              :   /// both code paths share the same parser.
     118            7 :   List<String>? _readLinuxProcNetArp() {
     119              :     try {
     120           14 :       final file = File(_linuxArpPath);
     121            7 :       if (!file.existsSync()) {
     122              :         return null;
     123              :       }
     124            7 :       final entries = <String>[];
     125           21 :       for (final line in file.readAsLinesSync().skip(1)) {
     126           21 :         final parts = line.trim().split(RegExp(r'\s+'));
     127           14 :         if (parts.length < 6) {
     128              :           continue;
     129              :         }
     130            7 :         final String ip = parts[0];
     131            7 :         final int? flags = int.tryParse(
     132           14 :           parts[2].replaceFirst('0x', ''),
     133              :           radix: 16,
     134              :         );
     135              :         // 0x2 is ATF_COM: the entry is complete and usable.
     136           14 :         if (flags == null || flags & 0x2 == 0) {
     137              :           continue;
     138              :         }
     139           28 :         entries.add('? ($ip) at ${parts[3]} [ether] on ${parts[5]}');
     140              :       }
     141              :       return entries;
     142              :     } catch (error, stackTrace) {
     143            0 :       arpLogger.fine("Unable to read /proc/net/arp: $error", error, stackTrace);
     144              :       return null;
     145              :     }
     146              :   }
     147              : 
     148            7 :   RegExp _getARPCmdRegExPattern() {
     149            7 :     if (isMacOSPlatform) {
     150            1 :       return RegExp(
     151              :         r'(?<host>[\w.?]*)\s\((?<ip>.*)\)\sat\s(?<mac>.*)\son\s(?<intf>\w+)\sifscope\s*(\w*)\s*\[(?<typ>.*)\]',
     152              :       );
     153            7 :     } else if (isLinuxPlatform) {
     154            7 :       return RegExp(
     155              :         r'(?<host>[\w.?]*)\s\((?<ip>.*)\)\sat\s(?<mac>.*)\s\[(?<typ>.*)\]\son\s(?<intf>\w+)',
     156              :       );
     157              :     } else {
     158              :       // Windows: non-greedy match and trim whitespace
     159            1 :       return RegExp(
     160              :         r'(?<ip>[^\s]+)\s+(?<mac>[^\s]+)\s+(?<typ>\w+)',
     161              :         caseSensitive: false,
     162              :       );
     163              :     }
     164              :   }
     165              : 
     166              :   /// Retrieves the ARP table by running the `arp -a` command on Linux, Windows, and macOS.
     167              :   ///
     168              :   /// Parses the output and returns a list of [ARPData] objects representing each ARP entry.
     169              :   /// Returns an empty list on unsupported platforms (e.g., Android, iOS).
     170            1 :   Future<List<ARPData>> buildTable() async {
     171            2 :     return _parseEntries(executeARPCommand());
     172              :   }
     173              : 
     174              :   /// Retrieves the ARP table without asking the OS to resolve host names.
     175              :   ///
     176              :   /// Host names are resolved separately for the hosts that were actually found,
     177              :   /// which is both faster and more reliable than the serial lookups performed
     178              :   /// by `arp -a`.
     179            7 :   Future<List<ARPData>> buildNumericTable() async {
     180           14 :     final int startTime = DateTime.now().millisecondsSinceEpoch;
     181           14 :     final entries = _parseEntries(executeNumericARPCommand());
     182           14 :     arpLogger.fine(
     183           35 :       "Numeric ARP read took ${DateTime.now().millisecondsSinceEpoch - startTime} ms with ${entries.length} entries",
     184              :     );
     185              :     return entries;
     186              :   }
     187              : 
     188              :   /// Asks the kernel to resolve link-layer addresses for [hosts] by sending a
     189              :   /// throwaway UDP datagram to each of them, then waits [settleDelay] so the
     190              :   /// neighbor table is populated before it is read.
     191              :   ///
     192              :   /// The datagrams never need an answer; they only trigger ARP resolution.
     193            1 :   Future<void> primeARPCache(
     194              :     Iterable<String> hosts, {
     195              :     Duration settleDelay = defaultPrimingDelay,
     196              :     int port = 9,
     197              :   }) async {
     198            2 :     if (!isARPSupported || hosts.isEmpty) {
     199              :       return;
     200              :     }
     201              :     RawDatagramSocket? socket;
     202              :     try {
     203            2 :       socket = await RawDatagramSocket.bind(InternetAddress.anyIPv4, 0);
     204              :       const List<int> payload = <int>[0];
     205            2 :       for (final host in hosts) {
     206            1 :         final address = InternetAddress.tryParse(host);
     207              :         if (address == null) {
     208              :           continue;
     209              :         }
     210            1 :         socket.send(payload, address, port);
     211              :       }
     212              :       // Give the kernel a moment to flush the datagrams before closing.
     213            1 :       await Future<void>.delayed(const Duration(milliseconds: 10));
     214              :     } catch (error, stackTrace) {
     215            0 :       arpLogger.fine(
     216            0 :         "Unable to prime the ARP cache: $error",
     217              :         error,
     218              :         stackTrace,
     219              :       );
     220              :     } finally {
     221            1 :       socket?.close();
     222              :     }
     223            1 :     await Future<void>.delayed(settleDelay);
     224              :   }
     225              : 
     226            7 :   List<ARPData> _parseEntries(List<String> entries) {
     227            7 :     final Map<String, ARPData> arpEntries = {};
     228           14 :     final int startTime = DateTime.now().millisecondsSinceEpoch;
     229            7 :     if (entries.isEmpty) {
     230            2 :       arpLogger.warning("No ARP entries found.");
     231            1 :       return [];
     232              :     }
     233              : 
     234            7 :     final pattern = _getARPCmdRegExPattern();
     235              : 
     236           14 :     for (final entry in entries) {
     237              :       // Skip Windows header and interface lines
     238           14 :       if (entry.trim().isEmpty ||
     239            7 :           entry.startsWith('Interface:') ||
     240           21 :           entry.trim().toLowerCase().startsWith('internet address')) {
     241              :         continue;
     242              :       }
     243            7 :       final match = pattern.firstMatch(entry);
     244              :       if (match == null) {
     245              :         continue;
     246              :       }
     247              :       try {
     248            7 :         final arpData = ARPData.fromRegExpMatch(match);
     249              :         // Localized headers can accidentally match the Windows pattern. Only
     250              :         // accept entries that actually contain a MAC address.
     251           14 :         final String? macAddress = _normalizeMacAddress(arpData.macAddress);
     252            7 :         if (macAddress == null || !_isUnicastMacAddress(macAddress)) {
     253            2 :           arpLogger.fine(
     254            1 :             "Skipping ARP entry with unusable MAC address: $entry",
     255              :           );
     256              :           continue;
     257              :         }
     258              :         // macOS prints octets without leading zeroes (e.g. d6:68:8b:9:0:7),
     259              :         // so pad them to keep MAC and vendor lookups consistent across
     260              :         // platforms.
     261            7 :         final ARPData normalized = ARPData(
     262            7 :           hostname: arpData.hostname,
     263            7 :           iPAddress: arpData.iPAddress,
     264              :           macAddress: macAddress,
     265            7 :           interfaceName: arpData.interfaceName,
     266            7 :           interfaceType: arpData.interfaceType,
     267            7 :           createdAt: arpData.createdAt,
     268              :         );
     269           21 :         arpLogger.fine("Adding entry to table -> $normalized");
     270           14 :         arpEntries[normalized.iPAddress] = normalized;
     271              :       } catch (error) {
     272            0 :         arpLogger.fine("Skipping unparsable ARP entry: $entry ($error)");
     273              :       }
     274              :     }
     275           14 :     arpLogger.fine(
     276           35 :       "ARP calculation took ${DateTime.now().millisecondsSinceEpoch - startTime} ms with ${arpEntries.length} entries",
     277              :     );
     278           14 :     return arpEntries.values.toList();
     279              :   }
     280              : 
     281              :   /// Accepts MAC addresses with or without leading zeroes per octet and
     282              :   /// returns a padded form, preserving the original separator. Returns null for
     283              :   /// `(incomplete)` entries and anything that is not a MAC address.
     284            7 :   static String? _normalizeMacAddress(String macAddress) {
     285           14 :     final List<String> parts = macAddress.split(RegExp('[:-]'));
     286           14 :     if (parts.length != 6) {
     287              :       return null;
     288              :     }
     289            7 :     final String separator = macAddress.contains('-') ? '-' : ':';
     290            7 :     final List<String> normalized = <String>[];
     291           14 :     for (final String part in parts) {
     292           14 :       if (!RegExp(r'^[0-9a-fA-F]{1,2}$').hasMatch(part)) {
     293              :         return null;
     294              :       }
     295           14 :       normalized.add(part.padLeft(2, '0'));
     296              :     }
     297            7 :     return normalized.join(separator);
     298              :   }
     299              : 
     300              :   /// Whether [macAddress] belongs to a single interface.
     301              :   ///
     302              :   /// Broadcast and multicast addresses are not devices: priming the cache
     303              :   /// creates a broadcast row for the subnet broadcast address, and Windows
     304              :   /// keeps multicast rows around.
     305            7 :   static bool _isUnicastMacAddress(String macAddress) {
     306              :     final List<int> octets = macAddress
     307           14 :         .split(RegExp('[:-]'))
     308           21 :         .map((part) => int.parse(part, radix: 16))
     309            7 :         .toList();
     310              :     // Bit 0 of the first octet is the group bit.
     311           14 :     if (octets[0].isOdd) {
     312              :       return false;
     313              :     }
     314           21 :     return octets.any((octet) => octet != 0);
     315              :   }
     316              : }
        

Generated by: LCOV version 2.0-1