Skip to content

Cross-VLAN Google Cast concept proof

Status: Confirmed working end-to-end. Casting from a phone on VLAN 26 to a Samsung TV on VLAN 2 succeeds, now running over the wired 802.1Q trunk (not the original WiFi-based setup).

Date proven: 2026-08-11 (original concept, using WiFi for the phone side) Date updated: 2026-08-17 (network re-architected to a dual-VLAN wired trunk through the Ruijie switch; reflector re-tested and confirmed working over the new tagged interfaces โ€” "it work perfectly for now everything is smooth"). Same day: added an IP-locked mode to restrict casting to one specific phone and one specific TV (see Section 5), later extended with an any wildcard for allow-all testing (Section 5.3), with real device IPs now recorded below. Date updated: 2026-08-18 (clarified exactly which discovery protocol this TV uses and what that means for which traffic the Mac mini actually bridges โ€” see Section 3.1).

Known device IPs for the IP-locked setup: - TV (VLAN 2, <VLAN2_SUBNET>): <TV_IP> โ€” discovered via SSDP/DIAL, not mDNS (see Section 3.1) - Phone (VLAN 26, <VLAN26_SUBNET>): <PHONE_IP>

(These are the real device addresses โ€” separate from the Mac mini's own two bridging addresses, <MACMINI_VLAN2_IP> / <MACMINI_VLAN26_IP>, used throughout this doc for the reflector's own interfaces.)


0. What changed since this was first proven

The original concept proof (2026-08-11) used two physically different interfaces: wired Ethernet (en0, untagged) for the TV's VLAN, and WiFi (en1) for the phone's VLAN, since at the time the phone network only existed over WiFi.

As of 2026-08-17, both VLANs now travel over the same physical Ethernet cable, tagged (802.1Q), through the Ruijie switch configured as a trunk. On the Mac mini, this means:

  • VLAN 2 (TV network, ) is now on the tagged interface vlan0 (macOS's internal name for the vlan2 network service), not en0. Plain en0 itself has no IP anymore.
  • VLAN 26 (phone network, ) is now on the tagged interface vlan1 (macOS's internal name for the vlan26 network service) โ€” this can run over the wired trunk instead of WiFi, though WiFi may still be connected as a fallback.

The reflector script itself needed no code changes for this โ€” it only takes interface names as command-line arguments, so this is purely a matter of passing vlan0/vlan1 instead of en0/en1. See Section 2.2 for the updated run command.


1. What you need before starting

1.1 Hardware / network setup (updated for the wired-trunk setup)

  • A machine that can have two separate network connections active at the same time, one landing on each VLAN you want to bridge. As of the current setup, the Mac mini uses:
  • vlan0 (tagged VLAN 2, riding over the physical en0 port) โ€” the TV's VLAN (the multicast/AV VLAN, <VLAN2_SUBNET>, VLAN ID 2 on the MikroTik, bridge BridgeMulticast, reaching the TV through the Ruijie switch's 802.1Q trunk).
  • vlan1 (tagged VLAN 26, also riding over the physical en0 port, same cable as above) โ€” the phone's VLAN (<VLAN26_SUBNET>, bridge bridge-wlan3).
  • Both VLANs now share the same physical cable and switch ports (MikroTik ether4 โ†’ Ruijie switch ports 0/1 and 0/11 โ†’ Mac mini), distinguished by 802.1Q tag rather than by using two different physical connections. This is a meaningful change from the original proof, where the two sides were genuinely separate links (wired vs. WiFi).
  • Confirm each interface actually landed on the IP range you expect:
    ifconfig vlan0
    ifconfig vlan1
    
    You should see vlan0 with <MACMINI_VLAN2_IP> and vlan: 2, and vlan1 with <MACMINI_VLAN26_IP> and vlan: 26, both status: active.
  • Note down the exact IP address assigned to each interface โ€” the script needs both, plus both interface names, as command-line arguments.

(If you're replicating this fresh and still using the older two-physical-links approach โ€” wired + WiFi โ€” the original interface names en0/en1 still apply; just substitute whatever your own interface names are. The script doesn't care whether the two sides are physically separate or are two tagged VLANs sharing one cable โ€” it only needs two distinct local IP addresses and interface names, one per side.)

1.2 MikroTik prerequisite: unicast routing already allowed between the two VLANs

This whole approach depends on normal unicast IP traffic already being permitted to route between the two VLANs โ€” it does NOT require multicast forwarding (the script substitutes for that). Before attempting any of this, confirm on the MikroTik:

  • The two VLAN bridges (BridgeMulticast and bridge-wlan3 in this setup) can already reach each other over plain unicast IP (e.g. ping from a device on one VLAN to a device on the other works).
  • No firewall filter rule is blocking general forward traffic between these two networks.

This was configured earlier in this project (address lists / firewall rules explicitly permitting BridgeMulticast and bridge-wlan3 to talk to each other) before any of the reflector work began. If you're replicating this on a fresh network, do this step first and confirm plain unicast ping works both directions before writing any code.

Note (2026-08-17): this blanket bridge-to-bridge allow is broader than most people want long-term โ€” it lets any device on VLAN 26 reach any device on VLAN 2, not just the one phone and one TV involved in casting. See Section 5.1 for how to narrow this down to a specific phone/TV pair once you know both IPs. As of this update, the decision made was to start with the discovery/script layer only (Section 5.2/5.3) and leave the MikroTik firewall untouched for now โ€” see Section 5.4 for what that choice does and doesn't cover.

1.3 Python (already included on macOS)

The final script only uses Python's standard library (socket, struct, select, threading, re, time) โ€” no pip install needed. Confirm Python 3 is available:

python3 --version

1.4 A dead end that was tried and abandoned โ€” do NOT install this

Skip this section entirely if you're just replicating the working setup. It's included only so nobody repeats the same wasted step. The final, working solution does not use this tool, does not need it installed, and has zero dependency on it.

Before writing the custom Python script that actually ended up working, an existing open-source tool called mdns-repeater was tried first, since it's the standard basic tool people reach for with this class of problem. It was cloned and an attempt was made to build it:

curl -L -o mdns-repeater.zip https://github.com/geekman/mdns-repeater/archive/refs/heads/master.zip
unzip mdns-repeater.zip
cd mdns-repeater-master
make

This failed to even compile on macOS, with an error about IP_PKTINFO / SOL_IP being undeclared โ€” IP_PKTINFO is a Linux-only socket option with no macOS/BSD equivalent, and mdns-repeater depends on it. It was abandoned at this point and never used for anything in the final solution.

Bottom line: no open-source tool is used anywhere in this project. The entire working solution is the one custom Python script described in this document, using only Python's built-in standard library. You do not need to install, clone, or build anything else.

(The only place this could matter later is a hypothetical Linux port โ€” see the note in section 4.4 โ€” but that's a future option, not something needed for what's already working.)


2. Step-by-step replication

2.1 Save the script

Create the file ~/mdns_reflect.py on the bridging machine with the exact contents given in the Appendix at the end of this document. (Easiest way on macOS: open Terminal and use cat > ~/mdns_reflect.py << 'PYEOF', paste the entire script body, then a line containing just PYEOF.)

2.2 Run it

sudo python3 ~/mdns_reflect.py <ip-on-VLAN-A> <interface-A> <ip-on-VLAN-B> <interface-B>

Current command, matching the wired-trunk setup (as of 2026-08-17):

sudo python3 ~/mdns_reflect.py <MACMINI_VLAN2_IP> vlan0 <MACMINI_VLAN26_IP> vlan1

(Original command from the first proof-of-concept, using WiFi for the phone side โ€” kept here for reference only, no longer what's actually run: sudo python3 ~/mdns_reflect.py <MACMINI_VLAN2_IP> en0 <MACMINI_VLAN26_IP> en1)

sudo is required because the script uses raw sockets to construct and spoof packets, which needs root.

Expected startup output (current setup):

Reflecting 224.0.0.251:5353 between <MACMINI_VLAN2_IP>(vlan0) <-> <MACMINI_VLAN26_IP>(vlan1)
Reflecting 239.255.255.250:1900 between <MACMINI_VLAN2_IP>(vlan0) <-> <MACMINI_VLAN26_IP>(vlan1)
DIAL/UPnP TCP proxies will be created automatically as targets are discovered.
Ctrl+C to stop.

Leave this running in its own terminal window and don't touch it further. It prints: - A periodic one-line summary roughly every 2 seconds when there's traffic (relayed=, delivered=, loop-skipped=). - [dial-proxy] lines whenever it rewrites a discovered address (either the initial SSDP LOCATION header, or an address found buried inside an HTTP response body). - [tcp-proxy] lines whenever a client actually connects through one of the dynamically created proxy ports, showing which real device address it's bridging to.

2.3 Test casting

On the phone: 1. Fully close the casting app (e.g. force-quit YouTube โ€” a simple back-out isn't enough, since some apps cache discovery results). 2. Reopen it. 3. Play any video. 4. Tap the Cast icon.

The TV should now appear in the device picker. Tap it โ€” casting should start and play on the TV.

Confirmed working (2026-08-17): ran exactly as above with the vlan0/vlan1 interfaces โ€” "it work perfectly for now everything is smooth."

2.4 Verifying each layer independently (useful if it's not working)

If casting doesn't work, verify each layer in isolation before assuming the whole thing is broken:

  1. Is the script actually running?
    ps aux | grep mdns_reflect
    
  2. Is the query even reaching the TV's network? Capture on the TV's interface while triggering Cast on the phone:
    sudo tcpdump -i vlan0 -n -X udp port 1900
    
    Look for a line with source = your phone's own address doing ST: urn:dial-multiscreen-org:service:dial:1 โ€” if you only ever see the reflector's own address (not the phone's), or nothing at all, the query relay itself isn't working.
  3. Is the TV replying at all? Capture just the TV's traffic:
    sudo tcpdump -i vlan0 -n host <tv-ip>
    
    during a Cast attempt. Some devices only reply on certain proprietary ports even when they ignore SSDP โ€” cross-check against a manual same-subnet query (see below) to establish a baseline of "the TV works normally at all."
  4. Manually query the TV directly (bypassing the phone) to establish a baseline. Run this on the bridging machine itself, using its own address on the TV's VLAN:
    python3 -c "
    import socket
    msg = (
        'M-SEARCH * HTTP/1.1\r\n'
        'HOST: 239.255.255.250:1900\r\n'
        'MAN: \"ssdp:discover\"\r\n'
        'MX: 2\r\n'
        'ST: urn:dial-multiscreen-org:service:dial:1\r\n'
        '\r\n'
    ).encode()
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(('<MACMINI_VLAN2_IP>', 0))
    s.sendto(msg, ('239.255.255.250', 1900))
    s.settimeout(3)
    try:
        while True:
            data, addr = s.recvfrom(4096)
            print('REPLY from', addr)
            print(data.decode(errors='replace'))
    except socket.timeout:
        print('done')
    "
    
    If this doesn't get a reply, the TV itself isn't answering SSDP right now (unrelated to any VLAN bridging) โ€” check the TV's own network settings/standby state first.
  5. Once discovery works, check the TCP proxy layer by watching for [tcp-proxy] lines in the running script's output at the moment you tap Cast โ€” absence of these means the phone never actually tried connecting through the rewritten address.

2.5 Stop it

Ctrl+C in the terminal running the script. No cleanup is needed โ€” it doesn't modify any system network settings.


3. What the script actually does (short version)

The Mac mini has two real addresses โ€” one on each VLAN. It never invents a fake address; it only ever uses these two.

  • Listens on both sides for discovery traffic (mDNS + SSDP multicast).
  • When a phone's query arrives, it remembers who asked, then re-sends that same query on the TV's side โ€” but using its own TV-side address, not the phone's. The TV answers because this looks like a normal local query.
  • When the TV's reply comes back, the script rewrites the LOCATION: address inside it to point at the Mac mini's own phone-side address (on a made-up local port), then hand-delivers that rewritten reply directly to the phone's real IP and port โ€” faked to look like it came straight from the TV, so the phone's app actually accepts it.
  • When the phone then connects to that rewritten address, the Mac mini accepts the connection, and separately opens its own new connection to the real TV using its TV-side address โ€” then just relays bytes between the two. On the way back, it also scans the TV's response for any further real addresses buried in the text (common in these device description documents) and rewrites those too, each getting its own dedicated local port.
  • Safety nets: a short-term memory of recently-relayed packets stops accidental infinite loops, and it only prints a short summary line every couple of seconds instead of flooding the terminal.

In short: one socket on each side, both using the Mac mini's own real addresses, translating text in both directions so neither side ever needs to know the other's real address directly. This logic is entirely independent of whether the two sides are physically separate links or two tagged VLANs sharing one cable โ€” the script only ever deals with IP addresses and interface names, never anything below that.

3.1 Important nuance: mDNS vs. SSDP โ€” this TV uses SSDP, and that's why unicast is fully covered

Note (2026-08-18): the script listens on both discovery protocols (mDNS on 224.0.0.251:5353 and SSDP on 239.255.255.250:1900), but it only does the full job โ€” bridging both the discovery multicast and the follow-up unicast โ€” for one of them, and it matters which one this TV actually uses.

  • mDNS (_googlecast._tcp, the native Chromecast/Google Cast discovery record): the script would only reflect the multicast query/reply. It does not parse or rewrite the DNS resource records inside an mDNS reply (there's no logic for that โ€” only the SSDP LOCATION: header and absolute URLs in HTTP bodies get rewritten). So if a device were discovered this way, the phone would learn the TV's real IP and port (typically 8009) straight from the mDNS answer, then connect to it directly, cross-VLAN, completely bypassing the Mac mini. That direct unicast connection only works today because the MikroTik still routes unicast freely between VLAN 2 and VLAN 26 (Section 1.2) โ€” the Mac mini isn't in that path at all.
  • SSDP/DIAL (ST: urn:dial-multiscreen-org:service:dial:1, port 1900) โ€” confirmed as what this TV actually uses: the script bridges both parts. It reflects the SSDP multicast query/reply and rewrites the LOCATION: header so the unicast follow-up (fetching the device description, then the DIAL app-launch/control requests) tunnels through the Mac mini's own dynamic TCP proxy ports (Section 3, bullet 4) rather than going phone-to-TV directly.

Practical takeaway for this setup: since the TV here is SSDP/DIAL-based, the Mac mini genuinely is in the path for the entire cast flow โ€” discovery and the unicast control traffic that follows it โ€” not just discovery. The mDNS-only-discovery caveat above is worth keeping in mind only if a different TV/device is ever added to this setup that discovers purely via mDNS/_googlecast._tcp instead of SSDP; for such a device, the Mac mini would only be covering the discovery half, and Section 5.1's MikroTik firewall rules would be the only way to actually control its unicast traffic.


4. Conclusion: why it works, and what to keep in mind

4.1 Two protection mechanisms caused this, not one

  1. Network-level: VLANs don't forward multicast. This is a normal, intentional feature of network segmentation, not a bug โ€” multicast discovery traffic (what Cast uses to find the TV) simply doesn't cross a VLAN boundary unless something explicitly relays it. This holds true regardless of whether the VLANs happen to share a physical cable (as in the current trunked setup) or use entirely separate links (as in the original WiFi-based proof) โ€” VLAN separation is a logical boundary, not a physical one.
  2. Device-level: the TV refuses to answer anything that looks off-subnet. This is the TV's own firmware being cautious, likely as an anti-spoofing measure. It shows up twice โ€” once when it silently ignores a discovery query claiming to be from outside its subnet, and again one layer deeper, because the TV's own discovery response contains further embedded addresses (for its actual app-launch and media services) that the phone would otherwise try to reach directly and get the same silent rejection.

Both are legitimate protections doing their job correctly โ€” the fix isn't "disabling" either one, it's having something with a genuinely valid address on each side do the asking/answering on everyone's behalf.

4.2 How the fix addresses each one

  • Mechanism 1 (no multicast forwarding) โ†’ the Mac mini physically re-broadcasts discovery traffic from one VLAN onto the other.
  • Mechanism 2, first occurrence (TV ignores off-subnet queries) โ†’ the Mac mini queries the TV using its own genuinely local address, then hand-delivers the TV's real answer straight to the phone's real address and port.
  • Mechanism 2, second occurrence (embedded addresses in the response) โ†’ the Mac mini also rewrites any further real addresses found inside the response body, proxying the resulting connections the same way, one dedicated local port per distinct real service.

4.3 Caveats

  • This ran by hand in a terminal on a Mac mini โ€” not a background service, no auto-restart, stops if the terminal closes or the machine sleeps.
  • Only tested with one TV and one app (YouTube); untested with multiple simultaneous targets.
  • The raw-socket code is macOS-specific โ€” a Linux port (e.g. onto the k3s server) would need that part rewritten, not just copied.
  • No cleanup of old proxy-port mappings over long runtimes; fine for a short test.
  • Both VLANs now share the same physical cable/switch ports (unlike the original proof) โ€” if that trunk ever goes down, both sides of the reflector lose connectivity simultaneously, whereas in the original wired+WiFi setup a link-layer problem on one side wouldn't necessarily affect the other.
  • This TV discovers via SSDP/DIAL, not mDNS (see Section 3.1) โ€” the script's full discovery+unicast coverage depends on that. A future device that only advertises via _googlecast._tcp mDNS would only get the discovery half bridged by this script; its unicast Cast session would rely entirely on the MikroTik's open unicast routing (Section 1.2) unless Section 5.1's firewall rules are applied to specifically allow it.

4.4 Suggested next steps

  1. Decide: keep it on the Mac mini, or port it to the k3s Linux server for an always-on setup.
  2. If porting to Linux, optionally pair Avahi's reflector (for plain mDNS) with a slimmed-down version of this script's DIAL-specific proxy logic.
  3. Package as a real service (systemd unit / k3s Deployment) with auto-restart.
  4. Add cleanup for stale proxy mappings if running long-term.
  5. Test with more devices/apps to see if the same approach generalizes.

5. Locking this down to one specific phone and one specific TV (2026-08-17)

The setup above is deliberately permissive: the MikroTik allows any device on VLAN 26 to reach any device on VLAN 2, and the reflector script relays discovery/proxy traffic for whichever devices happen to query it. If the goal is "only this one phone can cast to only this one TV" (given you already know both IPs from elsewhere โ€” e.g. a DHCP lease reservation), there are two layers that can be locked down. Doing both is the most thorough option; the firewall layer is the one that actually matters for security, the script layer is a second line of defense since it's easy to bypass by anyone who can reach the reflector machine directly. Current decision (see Section 5.4): started with the script/discovery layer only, MikroTik untouched for now.

5.1 Network layer (MikroTik firewall) โ€” the real control, not yet applied

This is what would actually restrict which devices can talk to which across the VLAN boundary, replacing the blanket allow from Section 1.2 โ€” not yet applied to the live MikroTik as of this update; kept here for when/if it's wanted:

/ip firewall address-list add list=cast-phone address=<PHONE_IP>
/ip firewall address-list add list=cast-tv address=<TV_IP>

/ip firewall filter add chain=forward src-address-list=cast-phone dst-address-list=cast-tv action=accept comment="phone->TV cast"
/ip firewall filter add chain=forward src-address-list=cast-tv dst-address-list=cast-phone action=accept comment="TV->phone cast"
/ip firewall filter add chain=forward in-interface=bridge-wlan3 out-interface=BridgeMulticast action=drop comment="block other phone-vlan->TV-vlan"
/ip firewall filter add chain=forward in-interface=BridgeMulticast out-interface=bridge-wlan3 action=drop comment="block other TV-vlan->phone-vlan"

Order matters in RouterOS โ€” rules are evaluated top to bottom and the first match wins, so the two accept rules must be positioned above the two drop rules (e.g. by adding them first, or with place-before). After this, no device other than the named phone/TV pair can route between the two VLANs at all โ€” this also means the reflector machine itself needs its own explicit allow if it's going to keep doing anything else across the VLAN boundary.

5.2 Script layer (mdns_reflect_locked.py) โ€” the layer currently in use

A modified version of the reflector adds two more required arguments โ€” the TV's IP and the phone's IP โ€” and uses them to ignore any multicast traffic from other sources, and to reject any TCP proxy connection not coming from the named phone. This is enforced in software only (an attacker with a spoofed source IP inside the LAN could bypass it, and it does nothing about direct unicast traffic that never touches the reflector โ€” see Section 5.4), which is why 5.1 is the layer that matters most if you ever want a true security boundary. For now, this script-only layer is what's actually running.

Argument order matters and is not interchangeable: <ip_A>/<iface_A> must be the Mac mini's own address/interface on the TV's VLAN, and <tv_ip> is only ever checked against traffic arriving on that same interface. Likewise <ip_B>/<iface_B> must be the Mac mini's own address/interface on the phone's VLAN, and <phone_ip> is only checked on that interface. Swapping the TV/phone info to the wrong side breaks the filter (it will either block everything or fail to match).

Usage:

sudo python3 ~/mdns_reflect_locked.py <own-ip-on-TV-vlan> <TV-vlan-iface> <own-ip-on-phone-vlan> <phone-vlan-iface> <tv-ip> <phone-ip>

Current command with real IPs filled in:

sudo python3 ~/mdns_reflect_locked.py <MACMINI_VLAN2_IP> vlan0 <MACMINI_VLAN26_IP> vlan1 <TV_IP> <PHONE_IP>

Expected startup line confirming the lock:

IP-locked: only TV=<TV_IP> (via vlan0) <-> phone=<PHONE_IP> (via vlan1) will be reflected/proxied.

To verify it's working: cast from the named phone as normal (should work exactly as before); try casting from a different phone on VLAN 26 (should never see the TV in the picker), and watch the periodic summary line's blocked(non-allowlisted)= counter tick up during that attempt, plus a [tcp-proxy] rejected connection from ... line if it gets far enough to try a proxy connection.

Full script source is in Appendix A, replacing the original mdns_reflect.py. The unlocked original is preserved in Appendix B for reference/rollback.

5.3 "any" wildcard for allow-all testing

The script also accepts the literal word any in place of <tv_ip> and/or <phone_ip>, disabling the filter on that side only. This is useful for an initial sanity check before locking to real IPs, or to temporarily reopen one side without editing the command structure:

sudo python3 ~/mdns_reflect_locked.py <MACMINI_VLAN2_IP> vlan0 <MACMINI_VLAN26_IP> vlan1 any any

With both sides set to any, this behaves identically to the original unlocked mdns_reflect.py โ€” the startup line will read IP-locked: only TV=any device (via vlan0) <-> phone=any device (via vlan1) will be reflected/proxied. Either side can be set independently, e.g. <TV_IP> any locks the TV side but leaves the phone side open.

5.4 What script-only locking does and doesn't cover (current state)

As of this update, only the script layer (5.2) is deployed โ€” the MikroTik firewall (5.1) has deliberately not been touched yet. Worth being precise about what that choice buys and what it leaves open, since it shapes what "only this phone can reach this TV" actually means right now:

  • What it stops: any other phone on VLAN 26 trying to discover/cast to the TV through the normal Cast-app flow. The reflector simply won't answer mDNS/SSDP queries for them, and won't hand out a working TCP proxy connection โ€” so the TV won't appear in their Cast picker at all.
  • What it doesn't stop: the MikroTik still permits ordinary unicast IP routing between the two VLAN bridges (from Section 1.2, still in effect). If some other device on VLAN 26 already knows the TV's real IP and port through some other means (not mDNS discovery), it could still open a direct connection to the TV, completely bypassing the Mac mini and this script's filter โ€” the reflector isn't in that traffic's path at all, so nothing on it can block that case.
  • Bottom line: script-only locking is a real, working control against casual/accidental discovery and casting from other devices, but it is not a hard access-control boundary. If that stronger guarantee is ever wanted, Section 5.1's MikroTik firewall rules are the only place that can enforce it, since the MikroTik is the only device actually routing between the two VLANs.

#!/usr/bin/env python3
"""
mDNS + SSDP reflector AND DIAL/UPnP TCP proxy for macOS.

IP-LOCKED VARIANT: only reflects/proxies traffic between one specific
phone IP and one specific TV IP. All other devices on either VLAN are
ignored, even if they can technically still reach this machine.

Discovery (SSDP/mDNS multicast):
  - Client M-SEARCH queries are relayed using the reflector's OWN
    same-subnet address (no spoofing), since many DIAL/UPnP devices
    silently refuse to answer queries that look off-subnet.
  - The device's real unicast reply is hand-delivered directly to the
    real client's IP:port, spoofed to look like it came from the device,
    so the client's app receives it on the exact port it's listening on.
  - If the reply contains a "LOCATION: http://<device-ip>:<port>/..."
    header, that address is rewritten to point at a per-target TCP proxy
    port on the reflector's own address, on the client's side.

DIAL/UPnP TCP proxy:
  - Each distinct (real device IP, real device port) seen in a LOCATION
    header gets its OWN dedicated local listening port (assigned
    automatically, starting at 20000), since a device can expose more
    than one service on different ports (e.g. DIAL app-launch vs. a
    separate media-control service) and they must not be collapsed
    onto a single shared port.
  - When the client connects to one of these local ports, the reflector
    opens an outbound connection to the *real* target using its own
    same-subnet address, and pipes bytes both ways -- from the device's
    perspective this looks like an ordinary same-subnet client.

IP locking (new):
  - Only multicast traffic whose source is the given TV IP (arriving on
    the TV-side interface) or the given phone IP (arriving on the
    phone-side interface) is processed at all. Traffic from any other
    device on either VLAN is silently ignored.
  - Only the given phone IP is allowed to connect through the dynamic
    TCP proxy ports; any other source is rejected and logged.
  - Pass the literal word "any" for <tv_ip> and/or <phone_ip> to disable
    filtering on that side (useful for an initial allow-all test run
    before locking down to real IPs). "any any" behaves like the
    original unlocked mdns_reflect.py.

Usage:
    sudo python3 mdns_reflect_locked.py <ip_A> <iface_A> <ip_B> <iface_B> <tv_ip> <phone_ip>

    <ip_A>/<iface_A> = this machine's own address/interface on the TV's VLAN
    <ip_B>/<iface_B> = this machine's own address/interface on the phone's VLAN
    <tv_ip>          = the TV's real IP address (only this address is trusted on the A side),
                        or "any" to allow any source on the A side
    <phone_ip>       = the phone's real IP address (only this address is trusted on the B side),
                        or "any" to allow any source on the B side
"""

import socket
import struct
import sys
import select
import time
import re
import threading

IP_HDRINCL = 2
IP_BOUND_IF = 25

GROUPS = [
    ("224.0.0.251", 5353),
    ("239.255.255.250", 1900),
]

SSDP_PORT = 1900
FIRST_PROXY_PORT = 20000

SEEN_TTL = 3.0
seen = {}

PENDING_TTL = 5.0
pending = {}

LOCATION_RE = re.compile(rb'(LOCATION:\s*http://)([\d\.]+):(\d+)', re.IGNORECASE)

target_map = {}
target_map_lock = threading.Lock()
next_proxy_port = [FIRST_PROXY_PORT]

# IP lock: set once in main(), read by the TCP proxy accept path.
ALLOWED_CLIENT_IP = None


def already_seen(src_ip, src_port, payload):
    now = time.monotonic()
    key = (src_ip, src_port, payload)
    last = seen.get(key)
    seen[key] = now
    if len(seen) > 2000:
        cutoff = now - SEEN_TTL
        for k in [k for k, t in seen.items() if t < cutoff]:
            del seen[k]
    if last is not None and (now - last) < SEEN_TTL:
        return True
    return False


def add_pending(own_if, client_ip, client_port):
    now = time.monotonic()
    lst = pending.setdefault(own_if, [])
    lst.append((client_ip, client_port, now + PENDING_TTL))
    pending[own_if] = [e for e in lst if e[2] > now]


def get_pending(if_name):
    now = time.monotonic()
    lst = pending.get(if_name, [])
    fresh = [e for e in lst if e[2] > now]
    pending[if_name] = fresh
    return fresh


def pipe(a, b):
    try:
        while True:
            data = a.recv(65536)
            if not data:
                break
            b.sendall(data)
    except OSError:
        pass
    finally:
        for sock in (a, b):
            try:
                sock.close()
            except OSError:
                pass


ABS_URL_RE = re.compile(rb'http://(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d+)')


def rewrite_absolute_urls(data, listen_ip, outbound_src_ip):
    def _sub(m):
        real_ip = m.group(1).decode()
        real_port = int(m.group(2))
        local_port = get_or_create_proxy(real_ip, real_port, listen_ip, outbound_src_ip)
        if (real_ip, real_port) not in _already_logged:
            _already_logged.add((real_ip, real_port))
            print(f"[dial-proxy] body reference {real_ip}:{real_port} -> advertising {listen_ip}:{local_port}")
        return b'http://' + listen_ip.encode() + b':' + str(local_port).encode()
    return ABS_URL_RE.sub(_sub, data)


_already_logged = set()


def recv_http_response(sock, timeout=5):
    sock.settimeout(timeout)
    buf = b""
    try:
        while b"\r\n\r\n" not in buf:
            chunk = sock.recv(4096)
            if not chunk:
                break
            buf += chunk
    except socket.timeout:
        pass
    if b"\r\n\r\n" not in buf:
        return None if not buf else (buf, b"")
    header_part, _, body_part = buf.partition(b"\r\n\r\n")
    content_length = None
    for line in header_part.split(b"\r\n"):
        if line.lower().startswith(b"content-length:"):
            try:
                content_length = int(line.split(b":", 1)[1].strip())
            except ValueError:
                content_length = None
    try:
        if content_length is not None:
            while len(body_part) < content_length:
                chunk = sock.recv(4096)
                if not chunk:
                    break
                body_part += chunk
        else:
            sock.settimeout(1.0)
            while True:
                chunk = sock.recv(4096)
                if not chunk:
                    break
                body_part += chunk
    except socket.timeout:
        pass
    return header_part, body_part


def rewrite_and_forward_responses(upstream, conn, listen_ip, outbound_src_ip):
    try:
        while True:
            result = recv_http_response(upstream, timeout=10)
            if result is None:
                break
            header_part, body_part = result
            if not header_part:
                break
            new_header = rewrite_absolute_urls(header_part, listen_ip, outbound_src_ip)
            new_body = rewrite_absolute_urls(body_part, listen_ip, outbound_src_ip)
            if re.search(rb'content-length:', new_header, re.IGNORECASE):
                new_header = re.sub(
                    rb'(?i)content-length:\s*\d+',
                    b'Content-Length: ' + str(len(new_body)).encode(),
                    new_header,
                )
            conn.sendall(new_header + b"\r\n\r\n" + new_body)
    except OSError:
        pass
    pipe(upstream, conn)


def handle_proxy_client(conn, addr, real_ip, real_port, outbound_src_ip, listen_ip):
    if ALLOWED_CLIENT_IP is not None and addr[0] != ALLOWED_CLIENT_IP:
        print(f"[tcp-proxy] rejected connection from {addr[0]} (only {ALLOWED_CLIENT_IP} is allowed)")
        try:
            conn.close()
        except OSError:
            pass
        return
    try:
        upstream = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        upstream.bind((outbound_src_ip, 0))
        upstream.settimeout(5)
        upstream.connect((real_ip, real_port))
        upstream.settimeout(None)
    except OSError as e:
        print(f"[tcp-proxy] connect to real target {real_ip}:{real_port} failed: {e}")
        conn.close()
        return
    print(f"[tcp-proxy] {addr} <-> {real_ip}:{real_port} (via {outbound_src_ip})")
    t1 = threading.Thread(target=pipe, args=(conn, upstream), daemon=True)
    t2 = threading.Thread(target=rewrite_and_forward_responses, args=(upstream, conn, listen_ip, outbound_src_ip), daemon=True)
    t1.start()
    t2.start()


def start_tcp_proxy(listen_ip, listen_port, real_ip, real_port, outbound_src_ip):
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    try:
        server.bind((listen_ip, listen_port))
    except OSError as e:
        print(f"[tcp-proxy] failed to bind {listen_ip}:{listen_port}: {e}")
        return
    server.listen(8)
    print(f"[tcp-proxy] new proxy: {listen_ip}:{listen_port} -> real {real_ip}:{real_port} (via {outbound_src_ip})")
    while True:
        conn, addr = server.accept()
        threading.Thread(target=handle_proxy_client, args=(conn, addr, real_ip, real_port, outbound_src_ip, listen_ip), daemon=True).start()


def get_or_create_proxy(real_ip, real_port, listen_ip, outbound_src_ip):
    key = (real_ip, real_port)
    with target_map_lock:
        if key in target_map:
            return target_map[key]
        local_port = next_proxy_port[0]
        next_proxy_port[0] += 1
        target_map[key] = local_port
    threading.Thread(
        target=start_tcp_proxy,
        args=(listen_ip, local_port, real_ip, real_port, outbound_src_ip),
        daemon=True,
    ).start()
    return local_port


def rewrite_location(data, listen_ip, outbound_src_ip):
    def _sub(m):
        real_ip = m.group(2).decode()
        real_port = int(m.group(3))
        local_port = get_or_create_proxy(real_ip, real_port, listen_ip, outbound_src_ip)
        print(f"[dial-proxy] LOCATION {real_ip}:{real_port} -> advertising {listen_ip}:{local_port}")
        return m.group(1) + listen_ip.encode() + b":" + str(local_port).encode()
    return LOCATION_RE.sub(_sub, data)


def checksum(msg):
    if len(msg) % 2:
        msg += b'\0'
    s = 0
    for i in range(0, len(msg), 2):
        s += (msg[i] << 8) + msg[i + 1]
    s = (s >> 16) + (s & 0xffff)
    s += (s >> 16)
    return ~s & 0xffff


def build_ip_udp_packet(src_ip, src_port, dst_ip, dst_port, payload):
    total_length = 20 + 8 + len(payload)
    ip_header = (
        struct.pack('!BB', (4 << 4) + 5, 0) +
        struct.pack('=H', total_length) +
        struct.pack('!HH', 54321, 0) +
        struct.pack('!BBH', 64, socket.IPPROTO_UDP, 0) +
        socket.inet_aton(src_ip) + socket.inet_aton(dst_ip)
    )
    csum = checksum(ip_header)
    ip_header = (
        struct.pack('!BB', (4 << 4) + 5, 0) +
        struct.pack('=H', total_length) +
        struct.pack('!HH', 54321, 0) +
        struct.pack('!BBH', 64, socket.IPPROTO_UDP, csum) +
        socket.inet_aton(src_ip) + socket.inet_aton(dst_ip)
    )
    udp_length = 8 + len(payload)
    udp_header = struct.pack('!HHHH', src_port, dst_port, udp_length, 0)
    return ip_header + udp_header + payload


def make_recv_socket(local_ip, group, port):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    if hasattr(socket, "SO_REUSEPORT"):
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
    s.bind(("", port))
    mreq = socket.inet_aton(group) + socket.inet_aton(local_ip)
    s.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
    s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.inet_aton(local_ip))
    s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 255)
    return s


def make_raw_socket(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
    s.setsockopt(socket.IPPROTO_IP, IP_HDRINCL, 1)
    ifidx = socket.if_nametoindex(ifname)
    s.setsockopt(socket.IPPROTO_IP, IP_BOUND_IF, struct.pack('I', ifidx))
    return s


def main():
    global ALLOWED_CLIENT_IP

    if len(sys.argv) != 7:
        print(f"Usage: sudo python3 {sys.argv[0]} <ip_A> <iface_A> <ip_B> <iface_B> <tv_ip> <phone_ip>")
        print("  <ip_A>/<iface_A> = this machine's own address/interface on the TV's VLAN")
        print("  <ip_B>/<iface_B> = this machine's own address/interface on the phone's VLAN")
        print("  <tv_ip>          = the TV's real IP (only this source is trusted on the A side), or 'any'")
        print("  <phone_ip>       = the phone's real IP (only this source is trusted on the B side), or 'any'")
        sys.exit(1)

    ip_a, if_a, ip_b, if_b, tv_ip, phone_ip = sys.argv[1:7]
    side_ip = {if_a: ip_a, if_b: ip_b}

    tv_filter_enabled = tv_ip.lower() != "any"
    phone_filter_enabled = phone_ip.lower() != "any"

    # ALLOWED_CLIENT_IP gates the TCP proxy accept path; None means "allow anyone".
    ALLOWED_CLIENT_IP = phone_ip if phone_filter_enabled else None

    recv_sockets = {}
    all_socks = []

    for group, port in GROUPS:
        sa = make_recv_socket(ip_a, group, port)
        sb = make_recv_socket(ip_b, group, port)
        recv_sockets[sa.fileno()] = (sa, ip_b, if_b, ip_a, if_a, group, port)
        recv_sockets[sb.fileno()] = (sb, ip_a, if_a, ip_b, if_b, group, port)
        all_socks.extend([sa, sb])
        print(f"Reflecting {group}:{port} between {ip_a}({if_a}) <-> {ip_b}({if_b})")

    raw_by_iface = {if_a: make_raw_socket(if_a), if_b: make_raw_socket(if_b)}

    tv_desc = tv_ip if tv_filter_enabled else "any device"
    phone_desc = phone_ip if phone_filter_enabled else "any device"
    print(f"IP-locked: only TV={tv_desc} (via {if_a}) <-> phone={phone_desc} (via {if_b}) will be reflected/proxied.")
    print("DIAL/UPnP TCP proxies will be created automatically as targets are discovered.")
    print("Ctrl+C to stop.")

    last_summary = time.monotonic()
    relay_count = 0
    skip_count = 0
    delivered_count = 0
    blocked_count = 0

    try:
        while True:
            ready, _, _ = select.select(all_socks, [], [], 1.0)
            for s in ready:
                recv_sock, other_ip, other_if, own_ip, own_if, group, port = recv_sockets[s.fileno()]
                data, addr = recv_sock.recvfrom(65535)
                src_ip, src_port = addr[0], addr[1]
                if src_ip == own_ip:
                    continue

                # --- IP lock: only the named TV (on the A/if_a side) and the
                # named phone (on the B/if_b side) are allowed through at all,
                # unless that side's filter was disabled with "any".
                if own_if == if_a and tv_filter_enabled and src_ip != tv_ip:
                    blocked_count += 1
                    continue
                if own_if == if_b and phone_filter_enabled and src_ip != phone_ip:
                    blocked_count += 1
                    continue

                if already_seen(src_ip, src_port, data):
                    skip_count += 1
                    continue

                if port == SSDP_PORT:
                    upper8 = data[:8].upper()
                    if upper8 == b"M-SEARCH":
                        add_pending(own_if, src_ip, src_port)
                        try:
                            send_sock = [x for x in all_socks if x.fileno() != s.fileno() and recv_sockets[x.fileno()][5] == group][0]
                            send_sock.sendto(data, (group, port))
                            relay_count += 1
                        except (OSError, IndexError) as e:
                            print(f"query relay error: {e}")
                    elif upper8.startswith(b"NOTIFY"):
                        try:
                            send_sock = [x for x in all_socks if x.fileno() != s.fileno() and recv_sockets[x.fileno()][5] == group][0]
                            send_sock.sendto(data, (group, port))
                            relay_count += 1
                        except (OSError, IndexError) as e:
                            print(f"notify relay error: {e}")
                    else:
                        clients = get_pending(other_if)
                        if clients:
                            rewritten = rewrite_location(data, side_ip[other_if], own_ip)
                        else:
                            rewritten = data
                        for client_ip, client_port, _exp in clients:
                            pkt = build_ip_udp_packet(src_ip, src_port, client_ip, client_port, rewritten)
                            try:
                                raw_by_iface[other_if].sendto(pkt, (client_ip, 0))
                                delivered_count += 1
                            except OSError as e:
                                print(f"deliver error: {e}")
                else:
                    try:
                        send_sock = [x for x in all_socks if x.fileno() != s.fileno() and recv_sockets[x.fileno()][5] == group][0]
                        send_sock.sendto(data, (group, port))
                        relay_count += 1
                    except (OSError, IndexError) as e:
                        print(f"send error: {e}")

            now = time.monotonic()
            if now - last_summary >= 2.0:
                if relay_count or skip_count or delivered_count or blocked_count:
                    print(f"[{time.strftime('%H:%M:%S')}] relayed={relay_count} delivered={delivered_count} loop-skipped={skip_count} blocked(non-allowlisted)={blocked_count}")
                relay_count = 0
                skip_count = 0
                delivered_count = 0
                blocked_count = 0
                last_summary = now
    except KeyboardInterrupt:
        print("\nStopping.")
    finally:
        for s in all_socks:
            s.close()
        for r in raw_by_iface.values():
            r.close()


if __name__ == "__main__":
    main()

Appendix B: original unlocked script source (mdns_reflect.py, macOS-specific, kept for reference/rollback)

(Unchanged from the original โ€” the script takes interface names/IPs as command-line arguments, so no code changes were needed for the earlier vlan0/vlan1 migration. See Section 2.2 for the run command. Superseded by Appendix A above for setups that want the IP lock; keep this version if you'd rather stay permissive.)

#!/usr/bin/env python3
"""
mDNS + SSDP reflector AND DIAL/UPnP TCP proxy for macOS.

Discovery (SSDP/mDNS multicast):
  - Client M-SEARCH queries are relayed using the reflector's OWN
    same-subnet address (no spoofing), since many DIAL/UPnP devices
    silently refuse to answer queries that look off-subnet.
  - The device's real unicast reply is hand-delivered directly to the
    real client's IP:port, spoofed to look like it came from the device,
    so the client's app receives it on the exact port it's listening on.
  - If the reply contains a "LOCATION: http://<device-ip>:<port>/..."
    header, that address is rewritten to point at a per-target TCP proxy
    port on the reflector's own address, on the client's side.

DIAL/UPnP TCP proxy:
  - Each distinct (real device IP, real device port) seen in a LOCATION
    header gets its OWN dedicated local listening port (assigned
    automatically, starting at 20000), since a device can expose more
    than one service on different ports (e.g. DIAL app-launch vs. a
    separate media-control service) and they must not be collapsed
    onto a single shared port.
  - When the client connects to one of these local ports, the reflector
    opens an outbound connection to the *real* target using its own
    same-subnet address, and pipes bytes both ways -- from the device's
    perspective this looks like an ordinary same-subnet client.

Usage:
    sudo python3 mdns_reflect.py <ip_A> <iface_A> <ip_B> <iface_B>
"""

import socket
import struct
import sys
import select
import time
import re
import threading

IP_HDRINCL = 2
IP_BOUND_IF = 25

GROUPS = [
    ("224.0.0.251", 5353),
    ("239.255.255.250", 1900),
]

SSDP_PORT = 1900
FIRST_PROXY_PORT = 20000

SEEN_TTL = 3.0
seen = {}

PENDING_TTL = 5.0
pending = {}

LOCATION_RE = re.compile(rb'(LOCATION:\s*http://)([\d\.]+):(\d+)', re.IGNORECASE)

target_map = {}
target_map_lock = threading.Lock()
next_proxy_port = [FIRST_PROXY_PORT]


def already_seen(src_ip, src_port, payload):
    now = time.monotonic()
    key = (src_ip, src_port, payload)
    last = seen.get(key)
    seen[key] = now
    if len(seen) > 2000:
        cutoff = now - SEEN_TTL
        for k in [k for k, t in seen.items() if t < cutoff]:
            del seen[k]
    if last is not None and (now - last) < SEEN_TTL:
        return True
    return False


def add_pending(own_if, client_ip, client_port):
    now = time.monotonic()
    lst = pending.setdefault(own_if, [])
    lst.append((client_ip, client_port, now + PENDING_TTL))
    pending[own_if] = [e for e in lst if e[2] > now]


def get_pending(if_name):
    now = time.monotonic()
    lst = pending.get(if_name, [])
    fresh = [e for e in lst if e[2] > now]
    pending[if_name] = fresh
    return fresh


def pipe(a, b):
    try:
        while True:
            data = a.recv(65536)
            if not data:
                break
            b.sendall(data)
    except OSError:
        pass
    finally:
        for sock in (a, b):
            try:
                sock.close()
            except OSError:
                pass


ABS_URL_RE = re.compile(rb'http://(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d+)')


def rewrite_absolute_urls(data, listen_ip, outbound_src_ip):
    def _sub(m):
        real_ip = m.group(1).decode()
        real_port = int(m.group(2))
        local_port = get_or_create_proxy(real_ip, real_port, listen_ip, outbound_src_ip)
        if (real_ip, real_port) not in _already_logged:
            _already_logged.add((real_ip, real_port))
            print(f"[dial-proxy] body reference {real_ip}:{real_port} -> advertising {listen_ip}:{local_port}")
        return b'http://' + listen_ip.encode() + b':' + str(local_port).encode()
    return ABS_URL_RE.sub(_sub, data)


_already_logged = set()


def recv_http_response(sock, timeout=5):
    sock.settimeout(timeout)
    buf = b""
    try:
        while b"\r\n\r\n" not in buf:
            chunk = sock.recv(4096)
            if not chunk:
                break
            buf += chunk
    except socket.timeout:
        pass
    if b"\r\n\r\n" not in buf:
        return None if not buf else (buf, b"")
    header_part, _, body_part = buf.partition(b"\r\n\r\n")
    content_length = None
    for line in header_part.split(b"\r\n"):
        if line.lower().startswith(b"content-length:"):
            try:
                content_length = int(line.split(b":", 1)[1].strip())
            except ValueError:
                content_length = None
    try:
        if content_length is not None:
            while len(body_part) < content_length:
                chunk = sock.recv(4096)
                if not chunk:
                    break
                body_part += chunk
        else:
            sock.settimeout(1.0)
            while True:
                chunk = sock.recv(4096)
                if not chunk:
                    break
                body_part += chunk
    except socket.timeout:
        pass
    return header_part, body_part


def rewrite_and_forward_responses(upstream, conn, listen_ip, outbound_src_ip):
    try:
        while True:
            result = recv_http_response(upstream, timeout=10)
            if result is None:
                break
            header_part, body_part = result
            if not header_part:
                break
            new_header = rewrite_absolute_urls(header_part, listen_ip, outbound_src_ip)
            new_body = rewrite_absolute_urls(body_part, listen_ip, outbound_src_ip)
            if re.search(rb'content-length:', new_header, re.IGNORECASE):
                new_header = re.sub(
                    rb'(?i)content-length:\s*\d+',
                    b'Content-Length: ' + str(len(new_body)).encode(),
                    new_header,
                )
            conn.sendall(new_header + b"\r\n\r\n" + new_body)
    except OSError:
        pass
    pipe(upstream, conn)


def handle_proxy_client(conn, addr, real_ip, real_port, outbound_src_ip, listen_ip):
    try:
        upstream = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        upstream.bind((outbound_src_ip, 0))
        upstream.settimeout(5)
        upstream.connect((real_ip, real_port))
        upstream.settimeout(None)
    except OSError as e:
        print(f"[tcp-proxy] connect to real target {real_ip}:{real_port} failed: {e}")
        conn.close()
        return
    print(f"[tcp-proxy] {addr} <-> {real_ip}:{real_port} (via {outbound_src_ip})")
    t1 = threading.Thread(target=pipe, args=(conn, upstream), daemon=True)
    t2 = threading.Thread(target=rewrite_and_forward_responses, args=(upstream, conn, listen_ip, outbound_src_ip), daemon=True)
    t1.start()
    t2.start()


def start_tcp_proxy(listen_ip, listen_port, real_ip, real_port, outbound_src_ip):
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    try:
        server.bind((listen_ip, listen_port))
    except OSError as e:
        print(f"[tcp-proxy] failed to bind {listen_ip}:{listen_port}: {e}")
        return
    server.listen(8)
    print(f"[tcp-proxy] new proxy: {listen_ip}:{listen_port} -> real {real_ip}:{real_port} (via {outbound_src_ip})")
    while True:
        conn, addr = server.accept()
        threading.Thread(target=handle_proxy_client, args=(conn, addr, real_ip, real_port, outbound_src_ip, listen_ip), daemon=True).start()


def get_or_create_proxy(real_ip, real_port, listen_ip, outbound_src_ip):
    key = (real_ip, real_port)
    with target_map_lock:
        if key in target_map:
            return target_map[key]
        local_port = next_proxy_port[0]
        next_proxy_port[0] += 1
        target_map[key] = local_port
    threading.Thread(
        target=start_tcp_proxy,
        args=(listen_ip, local_port, real_ip, real_port, outbound_src_ip),
        daemon=True,
    ).start()
    return local_port


def rewrite_location(data, listen_ip, outbound_src_ip):
    def _sub(m):
        real_ip = m.group(2).decode()
        real_port = int(m.group(3))
        local_port = get_or_create_proxy(real_ip, real_port, listen_ip, outbound_src_ip)
        print(f"[dial-proxy] LOCATION {real_ip}:{real_port} -> advertising {listen_ip}:{local_port}")
        return m.group(1) + listen_ip.encode() + b":" + str(local_port).encode()
    return LOCATION_RE.sub(_sub, data)


def checksum(msg):
    if len(msg) % 2:
        msg += b'\0'
    s = 0
    for i in range(0, len(msg), 2):
        s += (msg[i] << 8) + msg[i + 1]
    s = (s >> 16) + (s & 0xffff)
    s += (s >> 16)
    return ~s & 0xffff


def build_ip_udp_packet(src_ip, src_port, dst_ip, dst_port, payload):
    total_length = 20 + 8 + len(payload)
    ip_header = (
        struct.pack('!BB', (4 << 4) + 5, 0) +
        struct.pack('=H', total_length) +
        struct.pack('!HH', 54321, 0) +
        struct.pack('!BBH', 64, socket.IPPROTO_UDP, 0) +
        socket.inet_aton(src_ip) + socket.inet_aton(dst_ip)
    )
    csum = checksum(ip_header)
    ip_header = (
        struct.pack('!BB', (4 << 4) + 5, 0) +
        struct.pack('=H', total_length) +
        struct.pack('!HH', 54321, 0) +
        struct.pack('!BBH', 64, socket.IPPROTO_UDP, csum) +
        socket.inet_aton(src_ip) + socket.inet_aton(dst_ip)
    )
    udp_length = 8 + len(payload)
    udp_header = struct.pack('!HHHH', src_port, dst_port, udp_length, 0)
    return ip_header + udp_header + payload


def make_recv_socket(local_ip, group, port):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    if hasattr(socket, "SO_REUSEPORT"):
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
    s.bind(("", port))
    mreq = socket.inet_aton(group) + socket.inet_aton(local_ip)
    s.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
    s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.inet_aton(local_ip))
    s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 255)
    return s


def make_raw_socket(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
    s.setsockopt(socket.IPPROTO_IP, IP_HDRINCL, 1)
    ifidx = socket.if_nametoindex(ifname)
    s.setsockopt(socket.IPPROTO_IP, IP_BOUND_IF, struct.pack('I', ifidx))
    return s


def main():
    if len(sys.argv) != 5:
        print(f"Usage: sudo python3 {sys.argv[0]} <ip_A> <iface_A> <ip_B> <iface_B>")
        sys.exit(1)

    ip_a, if_a, ip_b, if_b = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]
    side_ip = {if_a: ip_a, if_b: ip_b}

    recv_sockets = {}
    all_socks = []

    for group, port in GROUPS:
        sa = make_recv_socket(ip_a, group, port)
        sb = make_recv_socket(ip_b, group, port)
        recv_sockets[sa.fileno()] = (sa, ip_b, if_b, ip_a, if_a, group, port)
        recv_sockets[sb.fileno()] = (sb, ip_a, if_a, ip_b, if_b, group, port)
        all_socks.extend([sa, sb])
        print(f"Reflecting {group}:{port} between {ip_a}({if_a}) <-> {ip_b}({if_b})")

    raw_by_iface = {if_a: make_raw_socket(if_a), if_b: make_raw_socket(if_b)}

    print("DIAL/UPnP TCP proxies will be created automatically as targets are discovered.")
    print("Ctrl+C to stop.")

    last_summary = time.monotonic()
    relay_count = 0
    skip_count = 0
    delivered_count = 0

    try:
        while True:
            ready, _, _ = select.select(all_socks, [], [], 1.0)
            for s in ready:
                recv_sock, other_ip, other_if, own_ip, own_if, group, port = recv_sockets[s.fileno()]
                data, addr = recv_sock.recvfrom(65535)
                src_ip, src_port = addr[0], addr[1]
                if src_ip == own_ip:
                    continue

                if already_seen(src_ip, src_port, data):
                    skip_count += 1
                    continue

                if port == SSDP_PORT:
                    upper8 = data[:8].upper()
                    if upper8 == b"M-SEARCH":
                        add_pending(own_if, src_ip, src_port)
                        try:
                            send_sock = [x for x in all_socks if x.fileno() != s.fileno() and recv_sockets[x.fileno()][5] == group][0]
                            send_sock.sendto(data, (group, port))
                            relay_count += 1
                        except (OSError, IndexError) as e:
                            print(f"query relay error: {e}")
                    elif upper8.startswith(b"NOTIFY"):
                        try:
                            send_sock = [x for x in all_socks if x.fileno() != s.fileno() and recv_sockets[x.fileno()][5] == group][0]
                            send_sock.sendto(data, (group, port))
                            relay_count += 1
                        except (OSError, IndexError) as e:
                            print(f"notify relay error: {e}")
                    else:
                        clients = get_pending(other_if)
                        if clients:
                            rewritten = rewrite_location(data, side_ip[other_if], own_ip)
                        else:
                            rewritten = data
                        for client_ip, client_port, _exp in clients:
                            pkt = build_ip_udp_packet(src_ip, src_port, client_ip, client_port, rewritten)
                            try:
                                raw_by_iface[other_if].sendto(pkt, (client_ip, 0))
                                delivered_count += 1
                            except OSError as e:
                                print(f"deliver error: {e}")
                else:
                    try:
                        send_sock = [x for x in all_socks if x.fileno() != s.fileno() and recv_sockets[x.fileno()][5] == group][0]
                        send_sock.sendto(data, (group, port))
                        relay_count += 1
                    except (OSError, IndexError) as e:
                        print(f"send error: {e}")

            now = time.monotonic()
            if now - last_summary >= 2.0:
                if relay_count or skip_count or delivered_count:
                    print(f"[{time.strftime('%H:%M:%S')}] relayed={relay_count} delivered={delivered_count} loop-skipped={skip_count}")
                relay_count = 0
                skip_count = 0
                delivered_count = 0
                last_summary = now
    except KeyboardInterrupt:
        print("\nStopping.")
    finally:
        for s in all_socks:
            s.close()
        for r in raw_by_iface.values():
            r.close()


if __name__ == "__main__":
    main()