Search code examples
macosfirewallnat

How to Redirect Incoming Traffic on Port to a Diff IP and Port on macOS?


I've been searching for this, but I'm having a bit of a difficult time finding exactly what it is that I want.

I have a Raspberry Pi behind a DHCP server running on my iMac (iMac is 192.168.2.1 to the pi, pi is 192.168.2.21). I want incoming traffic to the Mac (addr 10.5.6.4) to redirect to the pi (say port 8086 on the Mac would redirect to the pi port 22).

I tried adding "nat on en0 from any to any port 8086 -> 192.168.2.21 port 22" to the pf.conf file and reloading the service, but that didn't seem to accomplish anything. I have a very limited understanding of NAT and PF, so any and all help will be appreciated.

The purpose of this is so that other people on the network can connect to the Pi (and eventually other servers as well) using my Mac's IP and whatever port I specify. I know that there's a way to do it; I just don't know exactly how.


Solution

  • The solution that worked best for me was to use a reverse SSH tunnel.

    This is really easily done with a simple command.

    ssh -R <port to use on server>:localhost:<port to forward> <ip addr of server>
    

    So in my case it would be along the lines of (from the pi)

    ssh -R 8086:localhost:22 [email protected]
    

    I, again, don't know why my post got downvoted, but I'm happy that I at least found the solution that worked for me. By the way, ssh does use some cpu and adds some overhead because of the fact that it is a secure protocol and encrypts traffic. If you want to override that (if your system supports it) and use no encryption, use the "-c none" flag before -R. Also for multiple ports to be forwarded, just use multiple -R flags.

    ssh -c none -R 8086:localhost:22 -R 8080:localhost:80 [email protected]
    

    I hope this helps someone.