zapret-kvn/xray_fluent/network/connection_family.py
loop-uh 81b204b309
Some checks failed
Windows project source guards / test (push) Failing after 3m35s
Dashboard shows the address family of the server connection (OS TCP table or the helper's pinned address) and feeds the family memory so the ping follows it
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-29 07:17:22 -05:00

63 lines
2.9 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""По какому семейству адресов приложение подключено к VPN-серверу (IPv6 или IPv4).
Решение о семействе принимает ядро (гонка sing-box с памятью) или само приложение (Hysteria, Naive, Amnezia закрепляют адрес),
поэтому «по какому» читается из того, что получилось:
- сервер закреплён приложением — семейство закреплённого адреса (``pinned``);
- иначе — таблица ESTABLISHED TCP системы: у соединения с одним из адресов сервера удалённый адрес IPv6 или IPv4.
Это то, что видит ОС, без зондов в сеть и без патча ядра; UDP-соединения в этой таблице нет (Hysteria, WireGuard
закрепляют адрес сами и приходят через ``pinned``), вход через WARP даёт соединение к краю WARP, а не к серверу — тогда
ответ «неизвестно».
Только чтение локальных данных.
"""
from __future__ import annotations
import ipaddress
from typing import Iterable
LABELS = {4: "IPv4", 6: "IPv6"}
def family_of_connections(connections: Iterable[tuple[str, str]], addresses: Iterable[str]) -> int | None:
"""4 или 6 по соединениям с адресами сервера; ``None`` — ни одного. При обоих семействах — то, где соединений больше."""
known: set[ipaddress.IPv4Address | ipaddress.IPv6Address] = set()
for value in addresses:
try:
known.add(ipaddress.ip_address(str(value).split("%", 1)[0]))
except ValueError:
continue
counts = {4: 0, 6: 0}
for _path, remote in connections:
try:
address = ipaddress.ip_address(str(remote).split("%", 1)[0])
except ValueError:
continue
if address in known:
counts[address.version] += 1
if not counts[4] and not counts[6]:
return None
return 6 if counts[6] > counts[4] else 4
def observe(host: str, *, pinned: int | None = None) -> int | None:
"""Семейство текущего соединения с сервером ``host`` (4, 6 или ``None``)."""
if pinned in (4, 6):
return pinned
from . import latency_probe
from .bootstrap_dns import BootstrapDnsError
from ..platform.windows import running_programs
try:
addresses = latency_probe.server_addresses(host)
except (BootstrapDnsError, OSError):
return None
if not addresses:
return None
return family_of_connections(running_programs.established_connections(), addresses)
def label(family: int | None) -> str:
return LABELS.get(family or 0, "")