获取本机IP地址的小脚本

获取本机私网地址(1个)

 1 #!/bin/bash
 2 # Author      : standby
 3 # Date        : 2017-05-18
 4 # Description : Get private ip address of local machine.
 5 
 6 arr=(`/sbin/ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'|tr -d "addr:"`)
 7 #private_ip=${arr[0]}
 8 private_ip='0.0.0.0'
 9 
10 for ip in ${arr[*]};
11 do
12     ip_tmp=`echo $ip | grep '^10\.'`
13     if [[ ! -z $ip_tmp ]];then
14         private_ip=$ip_tmp
15         break
16     fi
17 done
18 [[ $private_ip == "0.0.0.0" ]] && echo "No private ip found!" || echo $private_ip

获取本机公网地址(1个或多个)

 1 #!/bin/bash
 2 # Author      : standby
 3 # Date        : 2017-05-18
 4 # Description : Get all public ip address of local machine.
 5 
 6 arr=(`/sbin/ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'|tr -d "addr:"`)
 7 #public_ip=${arr[0]}
 8 public_ip='0.0.0.0'
 9 
10 for ip in ${arr[*]}
11 do
12     ip_tmp=`echo $ip | grep -v '^10\.'`
13     if [[ ! -z $ip_tmp ]];then
14         public_ip=$public_ip$ip_tmp","
15         #break
16     fi
17 done
18 if [[ $public_ip == "0.0.0.0" ]]
19 then
20     echo "No public ip found!"
21 else
22     pub_arr=(`echo $public_ip |sed 's/0.0.0.0//g' |tr ',' '\n'`)
23     for ip in ${pub_arr[*]}
24     do
25         ip_tmp=`echo $ip | grep -vE '^192\.|^172\.'`
26         [[ ! -z $ip_tmp ]] && echo $ip_tmp
27     done
28 fi

 

posted @ 2017-05-18 14:02  lixin[at]hitwh  阅读(1768)  评论(0编辑  收藏  举报