差異處

這裏顯示兩個版本的差異處。

連向這個比對檢視

Both sides previous revision 前次修改
下次修改
前次修改
linux:shell_script:get_local_ip [2016/07/02 09:57]
tony
linux:shell_script:get_local_ip [2023/06/25 09:48] (目前版本)
行 1: 行 1:
 {{tag>​Linux ShellScript}} {{tag>​Linux ShellScript}}
 ====== 取得IP Address ====== ====== 取得IP Address ======
-===== ip cmd ===== +===== Introduction ===== 
-<​code ​sh>+網路上有許多教學告訴你如何透過ifconfig去取得ip address,而本篇教學主要分享我認為比較通用且簡單的做法。 
 +===== Get the interface list and check the cable status ​===== 
 +取得interface list方法很多種,除了可以透過ifconfig、ip等command外,先前我們是透過cat /​proc/​net/​dev的方式。但我認為透過list /​sys/​class/​net的方法比較簡單且通用:​ 
 +<​code ​bash> 
 +net_base=/​sys/​class/​net/​ 
 + 
 +for dev in ${net_base}*;​ do 
 +        dev_name=${dev##​*/​} 
 +        is_carrier=`cat ${dev}/​carrier` 
 +        echo ${dev_name} 
 +        echo ${is_carrier} 
 +done 
 +</​code>​ 
 +有幾個部分需要注意的,以eth0為例:​ 
 +  * dev變數為/​sys/​class/​net/​eth0的完整路徑,因此透過${dev##​*/​}的方式刪除以/​前最長的部分,即/​sys/​class/​net/​。 
 +  * /​sys/​class/​net/​eth0/​carrier如果在interface down的情況下,會出現如下圖錯誤;因此請先up後再做判斷。 
 +{{:​linux:​shell_script:​check_carrier_when_nic_down.png|}} 
 +===== Get IPv4 and IPv6 Address ===== 
 +許多教學都是透過ifconfig去達成,由於我們script需要能夠執行於Ubuntu Server的安裝環境下(無法用cut與awk),因此我使用ip command。 
 +<code bash> 
 +# 可在Ubuntu Server 14.04安裝環境下使用
 ip addr show | grep -o 'inet [0-9]\+\.[0-9]\+\.[0-9]\+\.[0-9]\+'​ | grep -o [0-9].* ip addr show | grep -o 'inet [0-9]\+\.[0-9]\+\.[0-9]\+\.[0-9]\+'​ | grep -o [0-9].*
 </​code>​ </​code>​
-可在Ubuntu Server 14.04安裝環境下使用 +如果要指定interface eth0: 
 +<code bash> 
 +ip addr show eth0 
 +</​code>​ 
 +ipv6比較難寫,我改使用以下方法,將不需要的部分去頭去尾:​ 
 +<code bash> 
 +ip=`ip addr show eth0 | grep -o 'inet6 .*'` 
 +ip=${ip%%/​*} 
 +ip=${ip#​inet6 } 
 +</​code>​
 ===== Reference ===== ===== Reference =====
   * [[http://​linux.vbird.org/​linux_basic/​0320bash.php|鳥哥 - 10.2.8 變數內容的刪除、取代與替換]]   * [[http://​linux.vbird.org/​linux_basic/​0320bash.php|鳥哥 - 10.2.8 變數內容的刪除、取代與替換]]
-  * [[http://​unix.stackexchange.com/​questions/​183760/​printing-interface-ipaddress-through-single-command-piped|Stackexchange ​- Printing interface-ipaddress through single command ]] +  * [[http://​unix.stackexchange.com/​questions/​183760/​printing-interface-ipaddress-through-single-command-piped|StackExchange ​- Printing interface-ipaddress through single command ]] 
 +  * [[http://​unix.stackexchange.com/​questions/​132621/​check-for-plugged-in-network-cable-on-startup|StackExchange - Check for plugged in network cable on startup]] 
 +=====    ===== 
 +---- 
 +\\ 
 +~~DISQUS~~