---
title: "perl中获取浮动ip"
author: "luogen33"
date: "2011-09-26T22:20:47Z"
tags: []
categories: ["编程语言"]
slug: "perl-ip"
draft: false
lastmod: "2011-09-26T22:20:47Z"
id: 1181013
url: "https://luogen33.iteye.com/blog/1181013"
---

通过strace ifconfig命令可以看到，linux实质是通过ioctl命令完成的网络接口ip获取。那么，我们也用ioctl就是了！

如下：

#!/usr/bin/perl
use strict;
use warnings;
use Socket;
require 'sys/ioctl.ph';
sub get_ip_address($) {
    my $pack = pack("a*", shift);
    my $socket;
    socket($socket, AF_INET, SOCK_DGRAM, 0);
    ioctl($socket, SIOCGIFADDR(), $pack);
    return inet_ntoa(substr($pack,20,4));
};
print get_ip_address("eth0");

这样的好处，就是只调用了核心模块，在分发脚本时，不用连带安装其他模块。