Parse ifconfig to get only my IP address using Bash

后端 未结 20 1213
甜味超标
甜味超标 2020-11-30 05:04

I want to edit the bashrc file to have a simple function called \"myip\" to run. As you might guess, the function myip prints only my internal IP address of my machine.

相关标签:
20条回答
  • 2020-11-30 05:54

    IPv4 Examples using BASH4+

    Example 1, using hostname:

      hostname -I|cut -d" " -f 1
    

    Example 2, the device is known (and it never changes) :

      ifconfig ens5 | grep "inet" | awk '{print $2}' |  sed 's/[^0-9.]*//g'
    

    Example 3, don't now the device (e.g. eth0, eth1, enp0s23, or wpxxx) :

     ip a | awk 'BEGIN{ "hostname -I|cut -d\" \" -f 1" | getline ip} $2 ~ ip {print "Device: "$NF "  IP: "$2}'
    

    Example 4, want the network IP address:

     wget -q -O /dev/stdout http://checkip.dyndns.org/ | cut -d":" -f2 | cut -d \< -f1
    

    enjoy.

    0 讨论(0)
  • 2020-11-30 05:57

    This works for me:
    ifconfig eth0 | awk '/inet addr/{print substr($2,6)}'

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