简体   繁体   English

如何从bash脚本确定IP地址?

[英]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? 如何以跨平台兼容的方式从Bash获取当前计算机的IP地址? I need to get the IP address the same way for Windows Linux and Mac OS. 对于Windows Linux和Mac OS,我需要以相同的方式获取IP地址。

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 我当前正在使用docker-compose创建完整部署的本地版本,但是无法使用localhost或127.0.0.1访问它,我必须引用当前计算机的IP地址,例如curl 192.168.0.23:80

Currently I make the user set the IP address manually: 目前,我让用户手动设置IP地址:

# 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. 但是,我希望能够在无需用户设置任何环境变量的情况下获得此功能,尤其是在处理Windows计算机时。

Any ideas? 有任何想法吗?

You need to detect host before use of the following because of OS specific commands 由于操作系统特定的命令,您需要在使用以下主机之前检测主机

Windows (Cygwin command line ) Windows(Cygwin命令行)

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 Linux的

LOCAL_IP=${LOCAL_IP:-`ifconfig | sed -En 's/127.0.0.1//;s/.*inet (addr:)?(([0-9]*\.){3}[0-9]*).*/\2/p'`}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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