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

后端 未结 29 1091
春和景丽
春和景丽 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:47
    hostname -I  
    

    This command will give you the exact ip address as you want in Ubuntu.

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

    You can also use the following command:

    ip route | grep src
    

    NOTE: This will only work if you have connectivity to the internet.

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

    I always wind up needing this at the most unexpected times and, without fail, wind up searching for threads like this on SO. So I wrote a simple script to get IPv4 addresses via netstat, called echoip - you can find it here. The bash for network addresses looks like this, it also gets your public address from ipecho.net:

    IPV4='\d+(\.\d+){3}'
    INTERFACES=`netstat -i | grep -E "$IPV4" | cut -d ' ' -f 1`
    INTERFACE_IPS=`netstat -i | grep -oE "$IPV4"`
    
    for i in "${!INTERFACES[@]}"; do
      printf "%s:\t%s\n" "${INTERFACES[$i]}" "${INTERFACE_IPS[$i]}"
    done
    

    The echoip script yields an output like this:

    $ echoip
    public: 26.106.59.169
    en0:    10.1.10.2
    
    0 讨论(0)
  • 2020-12-04 06:51
    #!/bin/sh
    # Tested on Ubuntu 18.04 and Alpine Linux 
    # List IPS of following network interfaces:
    # virtual host interfaces
    # PCI interfaces
    # USB interfaces
    # ACPI interfaces
    # ETH interfaces
    for NETWORK_INTERFACE in $(ls /sys/class/net -al | grep -iE "(/eth[0-9]+$|vif|pci|acpi|usb)" | sed -E "s@.* ([^ ]*) ->.*@\1@"); do 
        IPV4_ADDRESSES=$(ifconfig $NETWORK_INTERFACE | grep -iE '(inet addr[: ]+|inet[: ]+)' | sed -E "s@\s*(inet addr[: ]+|inet[: ]+)([^ ]*) .*@\2@")
        IPV6_ADDRESSES=$(ifconfig $NETWORK_INTERFACE | grep -iE '(inet6 addr[: ]+|inet6[: ]+)' | sed -E "s@\s*(inet6 addr[: ]+|inet6[: ]+)([^ ]*) .*@\2@")
        if [ -n "$IPV4_ADDRESSES" ] || [ -n "$IPV6_ADDRESSES" ]; then
            echo "NETWORK INTERFACE=$NETWORK_INTERFACE"
            for IPV4_ADDRESS in $IPV4_ADDRESSES; do 
                echo "IPV4=$IPV4_ADDRESS"
            done
            for IPV6_ADDRESS in $IPV6_ADDRESSES; do 
                echo "IPV6=$IPV6_ADDRESS"
            done
        fi
    done
    
    0 讨论(0)
  • 2020-12-04 06:51

    I would Use Hostname -L to get just the IP to use as a variable in a script.

    0 讨论(0)
提交回复
热议问题