Last active
September 4, 2019 00:58
-
-
Save exupero/4761833 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
domain=$1 | |
port=$2 | |
if [ -z "$domain" ] || [ -z "$port" ]; then | |
echo "Usage: domain-alias <domain> <port>" | |
exit 1 | |
fi | |
existing=$(cat /etc/hosts | grep "$domain$" | cut -d' ' -f1) | |
if [ -n "$existing" ]; then | |
ip=$existing | |
else | |
last=$(cat /etc/hosts | grep -oP "127.0.0.\d" | cut -d'.' -f4 | sort -n | tail -1) | |
next=$(expr $last + 1) | |
ip="127.0.0.$next" | |
fi | |
ipfwCmd="fwd $ip,$port tcp from any to $ip dst-port 80" | |
ifconfig lo0 alias $ip | |
# Add to ipfw rules. | |
ipfw list | grep -q "$ipfwCmd" | |
if [ "$?" -eq 1 ]; then | |
ipfw add $ipfwCmd > /dev/null | |
fi | |
# Append to /etc/ipfw.conf for persisting past restarts. | |
[[ ! -e /etc/ipfw.conf ]] && touch /etc/ipfw.conf | |
cat /etc/ipfw.conf | grep -q "$ipfwCmd" | |
if [ "$?" -eq 1 ]; then | |
echo "add $ipfwCmd # $domain" >> /etc/ipfw.conf | |
fi | |
# Append alias to local IP to /etc/hosts. | |
if [ -z "$existing" ]; then | |
echo "$ip $domain" >> /etc/hosts | |
fi | |
echo "Run apps at $ip:$port and view them at http://$domain/." |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ifconfig lo0 alias $ip | |
ipfw add fwd $ip,$port tcp from any to $ip dst-port 80 > /dev/null | |
echo "$ip $domain" >> /etc/hosts |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For newer versions of macOS, see https://apple.stackexchange.com/questions/254654/port-forwarding-on-macos-sierra