Which terminal command to get just IP address and nothing else?

后端 未结 29 1092
春和景丽
春和景丽 2020-12-04 06:16

I\'m trying to use just the IP address (inet) as a parameter in a script I wrote.

Is there an easy way in a unix terminal to get just the IP address, rather than loo

相关标签:
29条回答
  • 2020-12-04 06:32

    I wanted something simple that worked as a Bash alias. I found that hostname -I works best for me (hostname v3.15). hostname -i returns the loopback IP, for some reason, but hostname -I gives me the correct IP for wlan0, and without having to pipe output through grep or awk. A drawback is that hostname -I will output all IPs, if you have more than one.

    0 讨论(0)
  • 2020-12-04 06:33

    Command ifconfig is deprected and you should use ip command on Linux.

    Also ip a will give you scope on the same line as IP so it's easier to use.

    This command will show you your global (external) IP:

    ip a | grep "scope global" | grep -Po '(?<=inet )[\d.]+'
    

    All IPv4 (also 127.0.0.1):

    ip a | grep "scope" | grep -Po '(?<=inet )[\d.]+'
    

    All IPv6 (also ::1):

    ip a | grep "scope" | grep -Po '(?<=inet6 )[\da-z:]+'
    
    0 讨论(0)
  • 2020-12-04 06:34

    On latest Ubuntu versions (14.04 - 16.04), this command did the trick for me.

    hostname -I | awk '{print $1}'
    
    0 讨论(0)
  • 2020-12-04 06:34

    We can simply use only 2 commands ( ifconfig + awk ) to get just the IP (v4) we want like so:

    On Linux, assuming to get IP address from eth0 interface, run the following command:

    /sbin/ifconfig eth0 | awk '/inet addr/{print substr($2,6)}'
    

    On OSX, assumming to get IP affffdress from en0 interface, run the following command:

    /sbin/ifconfig en0 | awk '/inet /{print $2}'
    

    To know our public/external IP, add this function in ~/.bashrc

    whatismyip () {
        curl -s "http://api.duckduckgo.com/?q=ip&format=json" | jq '.Answer' | grep --color=auto -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b"
    }
    

    Then run, whatismyip

    0 讨论(0)
  • 2020-12-04 06:34

    That would do the trick in a Mac :

    ping $(ifconfig en0 | awk '$1 == "inet" {print $2}')
    

    That resolved to ping 192.168.1.2 in my machine.

    Pro tip: $(...) means run whatever is inside the parentheses in a subshell and return that as the value.

    0 讨论(0)
  • 2020-12-04 06:35

    You can write a script that only return the IP like:

    /sbin/ifconfig eth0 | grep 'inet addr' | cut -d: -f2 | awk '{print $1}'
    

    For MAC:

    ifconfig | grep "inet " | grep -v 127.0.0.1 | cut -d\  -f2
    

    Or for linux system

    hostname -i | awk '{print $3}' # Ubuntu 
    
    hostname -i # Debian
    
    0 讨论(0)
提交回复
热议问题