Skip to content

Instantly share code, notes, and snippets.

@exupero
Last active September 4, 2019 00:58
Show Gist options
  • Save exupero/4761833 to your computer and use it in GitHub Desktop.
Save exupero/4761833 to your computer and use it in GitHub Desktop.
#!/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/."
ifconfig lo0 alias $ip
ipfw add fwd $ip,$port tcp from any to $ip dst-port 80 > /dev/null
echo "$ip $domain" >> /etc/hosts
@exupero
Copy link
Author

exupero commented Apr 20, 2018

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