* remove needless hash check
[lab.git] / .bin / get_ip_from_ioctl.pl
1 #!/usr/bin/perl
2 use strict;
3 use warnings;
4 require 'sys/ioctl.ph';
5 use Socket;
6
7 my %interfaces;
8 my $max_addrs = 30;
9 socket(my $socket, AF_INET, SOCK_DGRAM, 0) or die "socket: $!";
10
11 {
12     my $ifreqpack = 'a16a16';
13     my $buf = pack($ifreqpack, '', '') x $max_addrs;
14     my $ifconf = pack('iP', length($buf), $buf);
15
16     # This does the actual work
17     ioctl($socket, SIOCGIFCONF(), $ifconf) or die "ioctl: $!";
18
19     my $len = unpack('iP', $ifconf);
20     substr($buf, $len) = '';
21
22     %interfaces = unpack("($ifreqpack)*", $buf);
23
24     unless (keys(%interfaces) < $max_addrs) {
25         # Buffer was too small
26         $max_addrs += 10;
27         redo;
28     }
29 }
30
31 for my $addr (values %interfaces) {
32     $addr = inet_ntoa((sockaddr_in($addr))[1]);
33 }
34
35 use Data::Dumper;
36 print Dumper \%interfaces;