1

How do I get the IPaddress of the current machine from Bash in a cross platform compatible way? I need to get the IP address the same way for Windows Linux and Mac OS.

I am currently using docker-compose to create a local version of my full deployment, however I can't access it using localhost or 127.0.0.1, I have to refer to the current machines IP address, for example curl 192.168.0.23:80

Currently I make the user set the IP address manually:

# Return true if we pass in an IPv4 pattern.
not_ip() {
  rx='([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])'

  if [[ $1 =~ ^$rx\.$rx\.$rx\.$rx$ ]]; then
    return 1
  else
    return 0
  fi
}

# Ensure lower case
OPTION=$(echo $1 | tr [:upper:] [:lower:])

case "$OPTION" in
"test")
    LOCAL_IP=${LOCAL_IP:-$2}

    if not_ip "$LOCAL_IP" ; then
      echo The test command couldn\'t resolve your computers Network IP. $LOCAL_IP
      echo
      help_comment
      exit 1
    fi
    python -m webbrowser "http://${LOCAL_IP}:80/" &
    ;;
esac

However I would love to be able to get this without having to have the user set any environment variables, especially when dealing with Windows machines.

Any ideas?

Andre Lewis
  • 396
  • 1
  • 4
  • 10

1 Answers1

1

You need to detect host before use of the following because of OS specific commands

Windows (Cygwin command line )

LOCAL_IP=${LOCAL_IP:-`ipconfig.exe | grep -im1 'IPv4 Address' | cut -d ':' -f2`}

MacOS

LOCAL_IP=${LOCAL_IP:-`ipconfig getifaddr en0`} #en0 for host and en1 for wireless

Linux

LOCAL_IP=${LOCAL_IP:-`ifconfig | sed -En 's/127.0.0.1//;s/.*inet (addr:)?(([0-9]*\.){3}[0-9]*).*/\2/p'`}
ntshetty
  • 1,293
  • 9
  • 20
  • I like this approach, the only downside is that docker itself creates quite a few virtual devices with their own IPv4 and IPv6 addresses. Unfortunately I will get back multiple address matches on every platform. From experience the MacOS answer will probably work consistently, as long as I know which interface they are actually using. – Andre Lewis Nov 13 '18 at 22:27