Linux通过命令仅获取IP地址的方法


    一同事的朋友正在参加笔试,遇到这么一个问题让他帮忙解决,结果同事又找到我帮他搞定。真是感慨:通讯发达在某些方面来说,真不知是不是好事啊!题目大致如下所示,一般我们使用ifconfig查看网卡信息,请问你可以通过什么命令,让其只输出IP地址192.168.42.128
    
    看似简单的问题,实现起来也不是太简单。看看下面的思路吧
    
[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来实现了,如下所示,到此问题解决。
    
[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;
}