How do you get loopback addresses other than 127.0.0.1 to work on OS X

According to everything I read, the entire 127.x.x.x subnet should loopback.

However, on my Mac, I can only ping 127.0.0.1

I know I've done this before (though possibly on another OS) and has come in very useful for developing multiple SSL sites locally and for tunneling remote services for access on a local IP (for example I could ssh into my MySQL server, and just port forward the standard port to the same port on my local machine but on 127.0.0.2 while my local server ran at 127.0.0.1.


Here is the short answer: sudo ifconfig lo0 alias 127.0.0.* up

Each alias must be added individually (sudo ifconfig lo0 alias 127.0.0.2 up, sudo ifconfig lo0 alias 127.0.0.3 up). It can be done manually for testing, or a subset or the complete list of the other 250 available numbers in that subnet can be made into StartupItems script that will do it automagically at boot time.

The long answer: According to RFC3330, 127.0.0.0/8 - This block is assigned for use as the Internet host loopback address. A datagram sent by a higher level protocol to an address anywhere within this block should loop back inside the host. This is ordinarily implemented using only 127.0.0.1/32 for loopback, but no addresses within this block should ever appear on any network anywhere.


For those interested, here is a little bash script that adds all the aliases for the IPs 127.0.0.*:

#!/bin/bash
for ((i=2;i<256;i++))
do
    sudo ifconfig lo0 alias 127.0.0.$i up
done

based on @laurent anwser and this article:

  1. Add localhost alias script:
$ sudo touch /usr/local/bin/localhost_alias
$ sudo chmod +x /usr/local/bin/localhost_alias
  1. localhost_alias content:
#!/usr/bin/env bash

from=${1}
to=${2}

if [[ -z "$from" || -z "$to" ]]; then
  echo "Usage: "`basename "$0"`" 2-255 2-255 [from and to range numbers (127.0.0.[from-to])]"
  exit 0
fi 

for ((i=${from};i<=${to};i++))
do
    sudo ifconfig lo0 alias 127.0.0.$i up
done
  1. add autorun daemon description:
$ sudo touch /Library/LaunchDaemons/org.localhost.alias.plist
  1. org.localhost.alias.plist content:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>org.localhost.alias</string>
    <key>RunAtLoad</key>
    <true/>
    <key>ProgramArguments</key>
    <array>
      <string>/usr/local/bin/localhost_alias</string>
      <string>2</string>
      <string>8</string>
    </array>
</dict>
</plist>
  1. And we have 127.0.0.2 - 127.0.0.8 aliases at boot

*Tested on MacOS Mojave.
** You must allow to run sudo script-name without password in sudoers file.