MacOS – Modify router port-forwarding rules from Terminal

macosNetworkrouterterminal

I'm trying to modify my router's NAT Table / Port-forwarding rules using the terminal on my Mac. My current setup looks something like this

Public  <->  Internet  <->  Modem + Router (1.1.1.1)  <->  Macbook (192.168.1.2)

There's a webserver / app running on port 7919 on my Macbook and I'd like to port-forward it so anyone can access it publicly from the internet. Specifically, I want 1.1.1.1:7919 to forward data to 192.168.1.2:7919.

I know I can do this by going in to the Router settings web interface, or using other GUI apps such as PortMap, but I need to do this using the command line.

I've been searching for a solution for hours and still haven't been able to find a simple solution that does this for me. The closest I came was to natd, but it has been deprecated in favor of pfctl, and I can't make any sense of it.

Best Answer

After searching for hours, I still wasn't able to find a built-in command-line utility that does what I'm asking for. But I did find something else that's pretty close. It's PortMapper, a java applet that comes with a command-line interface to manage the port-mappings of your router (must be UPnP compatible).

Since my plan was to do everything from the terminal, I'll walk you through the steps:

# Download the latest version
curl -fSL "https://sourceforge.net/projects/upnp-portmapper/files/latest/download" -o portmapper.jar

# See the basic help
java -jar portmapper.jar -h

# List all port-forwarding rules
java -jar portmapper.jar -list

# Create a new rule
java -jar portmapper.jar -add -externalPort 7919 -internalPort 7919 -ip 192.168.1.2 -protocol tcp

# Delete a rule
java -jar portmapper.jar -delete -externalPort 7919 -protocol tcp

This assumes you have java installed and available in your shell