For example, I run two websites on my macbook for development usage, and I want both of them to run on port 80 so that I don't have to type port numbers. (On web browser's url box, you can omit port number if it's 80.)
There may be other scenarios where you have to share one port between multiple programs.
Multiple program cannot share one IP-port pair, but they can share one port on different IPs!
If you already have multiple network interfaces on your machine, you can utilize them, but what if you do not have enough IPs?
You can use alias
like the following commands:
sudo ifconfig lo0 alias 10.0.0.1
sudo ifconfig lo0 alias 10.0.0.2
Now you have two new virtual IPs: 10.0.0.1
& 10.0.0.2
. They both point to localhost.
After rebooting, the virtual IPs will be lost. You can utilize crontab to make them persistent.
Use the following command to edit crontab jobs:
sudo crontab -e
In the editor, write the following jobs:
@reboot /sbin/ifconfig lo0 alias 10.0.0.1
@reboot /sbin/ifconfig lo0 alias 10.0.0.2
In the following chapters, I will show you a few examples of binding port.
Here we use python's http server to demonstrate:
sudo python3 -m http.server --bind 10.0.0.1 80
sudo python3 -m http.server --bind 10.0.0.2 80
Now two http servers with different IPs are sharing the same port 80. --bind
argument is used to specify binding IP.
Try to access them:
curl http://10.0.0.1
curl http://10.0.0.2
Sometimes I want to port forward two services to my macbook and the services should share the same port. Here's how I make that happen:
kubectl port-forward -n dev --address 10.0.0.1 service/mysql 3306:3306
kubectl port-forward -n test --address 10.0.0.2 service/mysql 3306:3306
Now two MySQL services with different IPs are sharing the same port 3306. --address
argument is used to specify binding IP.
Try to access them:
mysql -h 10.0.0.1
mysql -h 10.0.0.2