Hemanth.HM

A Computer Polyglot, CLI + WEB ♥'r.

Programmatically Accessing Network Interfaces

| Comments

This more of a self.note here, about programmatically accessing network interface.

Well, nothing can really beat ip addr show but here we go with few programming languages I like to paw at.

In Ruby 2.1:

1
2
3
4
5
require 'socket'

Socket.getifaddrs.each do |i|
  puts "#{i.name}: #{i.addr.ip_address}" if i.addr.ip?
end

In python:

Here I played with sockets but many python veterans suggest to use something like netifaces so did a pip install netifaces and then…

1
2
3
4
import netifaces

for face in netifaces.interfaces():
    print netifaces.ifaddresses(face)

In perl:

Similarly had to use Net::Interface package.

1
2
3
4
5
6
7
8
my %addresses = map {
      ($_ => [
          map { Net::Interface::inet_ntoa($_) }
              $_->address,
      ]);
} Net::Interface->interfaces;

print %addresses;

In nodejs:

Last but not the least, my current fav!

1
2
var os = require('os');
print os.networkInterfaces();

Well, there might always be better ways to do this, do share your way.

Comments