Linux通過命令僅獲取IP地址的方法
一同事的朋友正在參加筆試,遇到這么一個問題讓他幫忙解決,結(jié)果同事又找到我?guī)退愣?。真是感慨:通訊發(fā)達在某些方面來說,真不知是不是好事?。☆}目大致如下所示,一般我們使用ifconfig查看網(wǎng)卡信息,請問你可以通過什么命令,讓其只輸出IP地址192.168.42.128
看似簡單的問題,實現(xiàn)起來也不是太簡單。看看下面的思路吧
[root@DB-Server ~]# ifconfig eth0
eth0 Link encap:Ethernet HWaddr 00:0C:29:9E:70:0E
inet addr:192.168.42.128 Bcast:192.168.42.255 Mask:255.255.255.0
inet6 addr: fe80::20c:29ff:fe9e:700e/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:135 errors:0 dropped:0 overruns:0 frame:0
TX packets:216 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:14062 (13.7 KiB) TX bytes:26007 (25.3 KiB)
[root@DB-Server ~]# ifconfig eth0 | grep "inet addr"
inet addr:192.168.42.128 Bcast:192.168.42.255 Mask:255.255.255.0
到這一步非常簡單,接下來就需要借助awk來實現(xiàn)了,如下所示,到此問題解決。
[root@DB-Server ~]# ifconfig eth0 | grep "inet addr" | awk '{ print $2}'
addr:192.168.42.128
[root@DB-Server ~]# ifconfig eth0 | grep "inet addr" | awk '{ print $2}' | awk -F: '{print $2}'
192.168.42.128
PS: 獲取Linux下的IP地址
/**
* 獲取Linux下的IP地址
*
* @return IP地址
* @throws SocketException
*/
public static String getLinuxLocalIp() throws SocketException {
String ip = "";
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
String name = intf.getName();
if (!name.contains("docker") && !name.contains("lo")) {
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
String ipaddress = inetAddress.getHostAddress().toString();
if (!ipaddress.contains("::") && !ipaddress.contains("0:0:")
&& !ipaddress.contains("fe80")) {
ip = ipaddress;
}
}
}
}
}
} catch (SocketException ex) {
System.out.println("獲取ip地址異常");
ex.printStackTrace();
}
System.out.println("IP:" + ip);
return ip;
}
總結(jié)
以上所述是小編給大家介紹的Linux通過命令僅獲取IP地址的方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
window10系統(tǒng)安裝Ubuntu18.04系統(tǒng)的圖文教程詳解
這篇文章主要介紹了window10系統(tǒng)安裝Ubuntu18.04系統(tǒng),本文圖文并茂給大家介紹的非常詳細,具有一定的參考借鑒價值 ,需要的朋友可以參考下2019-06-06
Linux環(huán)境中使用Ext3文件系統(tǒng)
Linux環(huán)境中使用Ext3文件系統(tǒng)...2006-10-10
Linux系統(tǒng)如何添加普通用戶到 sudoers 文件
這篇文章主要介紹了Linux系統(tǒng)添加普通用戶到 sudoers 文件的方法,在文章給大家補充Debian將普通用戶添加到sudoer文件的方法,感興趣的朋友一起看看吧2017-10-10



