Method 1: ifconfig -a
Ifconfig -a | grep inet | grep -v 127.0.0.1 | grep -v inet6 | awk '{print $2}' | tr -d "addr:"Copy the code
The command to explain
- Ifconfig -a returns all IP addresses of the local host in the same way that the command is executed in Windows
- Grep inet intercepts the line containing IP
- Grep -v 127.0.0.1 to remove the locally pointed line
- Grep -v inet6 Remove the line containing inet6
- Awk {print $2} $2
- Tr -d “addr: Delete the string “addr:”
Multiple network cards
If there are multiple network adapters, there may be multiple IP addresses in different network segments. If you run the preceding command, multiple IP addresses will be returned as follows:
Suppose a machine has IP addresses in network segments 192.*.* 8 and 10.*.*.*
1 #! / bin/sh 2 IP = ` ifconfig -a | grep inet | grep -v 127.0.0.1 | grep -v inet6 | awk '{print $2}' | tr -d addr: "" three ` echo $4 if IP [[ IP = = $10. "" *]] 5 then 6 echo" the network segment is 10. *. *. * segment "7 8 echo the else" the network segment is 192. *. *. * segment "9 fiCopy the code
Method 2: IP addr
ip addr | awk ‘/^[0-9]+: / {}; /inet.*global/ {print gensub(/(.*)\/(.*)/, “\\1”, “g”, $2)}’
The awK command is used to create the awK command. The awK command is used to create the AWK command