欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Linux通過(guò)命令僅獲取IP地址的方法

 更新時(shí)間:2017年10月23日 10:57:09   作者:瀟湘隱者  
這篇文章主要介紹了Linux通過(guò)命令僅獲取IP地址的方法,需要的朋友可以參考下

一同事的朋友正在參加筆試,遇到這么一個(gè)問(wèn)題讓他幫忙解決,結(jié)果同事又找到我?guī)退愣?。真是感慨:通訊發(fā)達(dá)在某些方面來(lái)說(shuō),真不知是不是好事?。☆}目大致如下所示,一般我們使用ifconfig查看網(wǎng)卡信息,請(qǐng)問(wèn)你可以通過(guò)什么命令,讓其只輸出IP地址192.168.42.128

看似簡(jiǎn)單的問(wèn)題,實(shí)現(xiàn)起來(lái)也不是太簡(jiǎn)單??纯聪旅娴乃悸钒?/p>

[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

到這一步非常簡(jiǎn)單,接下來(lái)就需要借助awk來(lái)實(shí)現(xiàn)了,如下所示,到此問(wè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通過(guò)命令僅獲取IP地址的方法,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!

相關(guān)文章

最新評(píng)論