简体   繁体   中英

How can I determine the IP address from a bash script?

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?

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'`}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM