Skip to content

Instantly share code, notes, and snippets.

@shigenobuokamoto
Last active June 24, 2024 15:29
Show Gist options
  • Save shigenobuokamoto/b565d468541fc8be7d7d76a0434496a0 to your computer and use it in GitHub Desktop.
Save shigenobuokamoto/b565d468541fc8be7d7d76a0434496a0 to your computer and use it in GitHub Desktop.
/etc/systemd/system/network-mirrored.service
[Unit]
Wants=network-pre.target
Before=network-pre.target shutdown.target
[Service]
User=root
ExecStart=/bin/sh -ec '\
[ -x /usr/bin/wslinfo ] && [ "$(/usr/bin/wslinfo --networking-mode)" = "mirrored" ] || exit 0;\
echo "\
add chain ip nat WSLPREROUTING { type nat hook prerouting priority dstnat - 1; policy accept; };\
insert rule ip nat WSLPREROUTING iif loopback0 ip daddr 127.0.0.1 counter dnat to 127.0.0.1 comment mirrored;\
"|nft -f -\
'
ExecStop=/bin/sh -ec '\
[ -x /usr/bin/wslinfo ] && [ "$(/usr/bin/wslinfo --networking-mode)" = "mirrored" ] || exit 0;\
for chain in "ip nat WSLPREROUTING";\
do\
handle=$(nft -a list chain $chain | sed -En "s/^.*comment \\"mirrored\\" # handle ([0-9]+)$/\\1/p");\
for n in $handle; do echo "delete rule $chain handle $n"; done;\
done|nft -f -\
'
RemainAfterExit=yes
[Install]
WantedBy=multi-user.target
@trungly1
Copy link

trungly1 commented Jun 6, 2024

you can try it.

$ sudo systemctl --now enable network-mirrored

Very grateful for this, spent countless hours trying to figure it out, no amount of gpt could save me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment