listAcceptedAddressesOnTCPPorts method

  1. @override
Future<Set<(String, int)>> listAcceptedAddressesOnTCPPorts({
  1. bool sudo = false,
  2. Set<int>? allowedPorts,
})
override

Lists all the currently accepted addresses on TCP ports.

  • sudo: A flag indicating if sudo privileges should be used. Defaults to false.
  • allowedPorts: A set of allowed ports, or null to allow all ports.

Returns a Future that completes with a Set of (address,port) entries.

Implementation

@override
Future<Set<(String, int)>> listAcceptedAddressesOnTCPPorts(
    {bool sudo = false, Set<int>? allowedPorts}) async {
  final iptablesBin = await resolveBinaryPathCached('iptables');
  final iptablesArgs = <String>['-L', 'INPUT', '-n', '-v'];

  var output = await runCommand(
    iptablesBin,
    iptablesArgs,
    sudo: sudo,
    expectedExitCode: 0,
  );

  if (output == null || output.isEmpty) return {};

  final regExpAddress =
      RegExp(r'ACCEPT\s+(?:tcp|6|4)\s+--\s+\*\s+\*\s+(\S+)');
  final regExpPort = RegExp(r'dpt:(\d\d+)');

  final accepts = <(String, int)>{};

  for (final line in output.split('\n')) {
    if (line.contains('ACCEPT')) {
      final matchAddress = regExpAddress.firstMatch(line);
      final matchPort = regExpPort.firstMatch(line);
      if (matchAddress != null && matchPort != null) {
        var address = matchAddress.group(1)!;
        var gPort = matchPort.group(1)!;
        var port = int.tryParse(gPort.trim());
        if (address.isNotEmpty && port != null && port >= 10) {
          accepts.add((address, port));
        }
      }
    }
  }

  if (allowedPorts != null) {
    accepts.removeWhere((e) => !allowedPorts.contains(e.$2));
  }

  return accepts;
}