linux下使用perl获取本机ip的几种方法介绍

2019-09-23 09:47:29于丽

        socket($socket, AF_INET, SOCK_DGRAM, 0);
        ioctl($socket, SIOCGIFADDR(), $pack);
        return inet_ntoa(substr($pack,20,4));
    };
    print get_ip_address("eth0");

这样的好处,就是只调用了核心模块,在分发脚本时,不用连带安装其他模块。

注:这个其实是根据网上有的一个 py 的脚本修改的

py版如下:


#!/usr/bin/python
    import socket
    import fcntl
    import struct
    def get_ip_address(ifname):
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        return socket.inet_ntoa(fcntl.ioctl(
                s.fileno(),
                0x8915,  # SIOCGIFADDR
                struct.pack('256s', ifname[:15])
        )[20:24])
    print get_ip_address('eth0')

2012年12月19日增:
为logstash的input/file.rb找到。
ruby版本的:

#!/usr/bin/ruby
    require 'socket' 
    SIOCGIFADDR    = 0x8915          # get PA address           
    def get_ip_address(iface) 
      begin 
        sock = UDPSocket.new 
        buf = [iface,""].pack('a16h16') 
        sock.ioctl(SIOCGIFADDR, buf); 
        sock.close 
        buf[20..24].unpack("CCCC").join(".") 
      rescue 
        nil 
      end 
    end 
    if $0 == __FILE__ 
      puts get_ip_address('eth0') 
    end

不过看puppet里还是用ifconfig的方法,大家有时间可以搜索下相关内容。