How to Set Port Forwarding for Internet Sharing on Mac OS X Using pf
This concise guide will walk you through the process of setting up port forwarding on OS X utilizing pf, a built-in and robust packet filter module.
Imagine a scenario where you’re sharing Ethernet on a Mac via Wi-Fi with your phone and want to access port 8080 on your phone via the Mac’s Ethernet.
Initially, you’ll need to modify the /etc/pf.conf file. To do so, append the following lines:
anchor "custom"
load anchor "custom" from "/etc/pf.anchors/custom"In this context, “custom” signifies the name of the anchor, which can be altered according to your preferences. The path following from - /etc/pf.anchors/custom - will store the port forwarding rules we're about to introduce. If desired, you can specify a different file path.
Get Jeffrey Zhuang’s stories in your inbox
Join Medium for free to get updates from this writer.
Next, generate a file at "/etc/pf.anchors/custom" and incorporate the rule for port forwarding. As an example, suppose your Mac utilizes the en0 interface for the Ethernet. If you're uncertain about which interface is in use, you can scrutinize the output of the ifconfig command and identify the interface by its associated IP address. For this guide, we'll presume the en0 interface is in use. To forward the 8080 TCP port on your Mac to the port 8080 on your phone (whose IP, for the sake of this guide, is 192.168.2.10), you'll need to add the following line:
rdr pass on en0 inet proto tcp from any to any port 8080 -> 192.168.2.10 port 8080Subsequently, execute the following command to load the new rules from the recently added “custom” anchor:
pfctl -f /etc/pf.confTo verify if the rules have been successfully incorporated, use pfctl -a custom -sn, where "custom" denotes the anchor name.
Upon successful addition, the output should resemble:
# pfctl -a custom -sn
No ALTQ support in kernel
ALTQ related functions disabled
rdr pass on en0 inet proto tcp from any to any port = 8080 -> 192.168.2.10 port 8080Should you ever decide to discontinue port forwarding, the rules on the anchor can be removed via the anchor name using pfctl -a custom -F all. Following this, you can edit the /etc/pf.conf file to delete the two lines that were added earlier. Lastly, delete the /etc/pf.anchors/custom file.





