JJ_MKVMaker/lib/core/lan_scan.dart

79 lines
2.7 KiB
Dart

import 'dart:async';
import 'dart:io';
/// X-plore 비교 j: 같은 망에서 SMB (445) 서버 찾기 - 이 기기의 IPv4 망 (/24) 을 짧은 연결 시도로 훑는다.
/// 연결만 해 보고 바로 닫는다 (아무것도 보내지 않음). 찾은 것은 이름 (역방향 조회, 모르면 null) 과 함께.
/// SMB 서버 추가 창 (88 Android SMB) 의 [찾기] 에서 쓴다.
class LanHost {
final String address;
final String? name;
const LanHost(this.address, this.name);
}
/// 이 기기의 사설 IPv4 주소들 (Wi-Fi · 유선 · Tailscale 은 빼고 - 100.64/10 은 넓어 훑지 않는다)
Future<List<InternetAddress>> localPrivateIPv4() async {
final out = <InternetAddress>[];
for (final ni in await NetworkInterface.list(type: InternetAddressType.IPv4)) {
for (final a in ni.addresses) {
final b = a.rawAddress;
final private = b[0] == 10 || (b[0] == 172 && b[1] >= 16 && b[1] <= 31) || (b[0] == 192 && b[1] == 168);
if (private && !a.isLoopback) out.add(a);
}
}
return out;
}
/// [hosts] 의 [port] 가 열려 있는지 동시에 [parallel] 개씩 본다. 열린 것만 (주소 순서대로)
Future<List<LanHost>> scanPort(
List<String> hosts, {
int port = 445,
Duration timeout = const Duration(milliseconds: 400),
int parallel = 64,
bool Function()? cancelled,
void Function(int done, int total)? onProgress,
bool lookupNames = true,
}) async {
final open = <String>{};
var next = 0, done = 0;
Future<void> worker() async {
while (next < hosts.length) {
if (cancelled?.call() ?? false) return;
final h = hosts[next++];
try {
final s = await Socket.connect(h, port, timeout: timeout);
open.add(h);
s.destroy();
} catch (_) {}
onProgress?.call(++done, hosts.length);
}
}
await Future.wait([for (var i = 0; i < parallel; i++) worker()]);
final sorted = hosts.where(open.contains).toList();
final out = <LanHost>[];
for (final h in sorted) {
String? name;
if (lookupNames) {
try {
final r = await InternetAddress(h).reverse().timeout(const Duration(seconds: 1));
if (r.host != h) name = r.host;
} catch (_) {}
}
out.add(LanHost(h, name));
}
return out;
}
/// 이 기기의 사설망 (/24 마다) 의 SMB 서버들
Future<List<LanHost>> findSmbServers({bool Function()? cancelled, void Function(int done, int total)? onProgress}) async {
final hosts = <String>[];
for (final a in await localPrivateIPv4()) {
final b = a.rawAddress;
for (var i = 1; i < 255; i++) {
final h = '${b[0]}.${b[1]}.${b[2]}.$i';
if (!hosts.contains(h)) hosts.add(h);
}
}
return scanPort(hosts, cancelled: cancelled, onProgress: onProgress);
}