1

in C++ linux application, how can I get the network interface reffering to each IP on my machine? IP contains: static IP and dynamic IP

Note: I can't use the system call getnameinfo

10x

gln
  • 1,011
  • 5
  • 31
  • 61
  • Prob this question can help you: http://stackoverflow.com/questions/212528/linux-c-get-the-ip-address-of-local-computer – Tony The Lion Jan 24 '11 at 11:45

2 Answers2

3

You can use the getifaddrs call; however, note that this only retrieves one address per interface. If that's not sufficient, use the rtnetlink protocol over a netlink socket; libnetlink may make this easier.

bdonlan
  • 224,562
  • 31
  • 268
  • 324
  • 3
    `getifaddrs()` is implemented (on Linux) using netlink. It's the right interface (and it can return multiple addresses per interface - they just appear in multiple `struct ifaddrs`). – caf Jan 24 '11 at 12:59
2

It's quite tricky to do this, I believe you need to have root access. You need to issue an ioctl (something like SIOCGIFCONF) which then returns you a list of all interfaces, and then you can issue further ioctl calls to extract status information, etc.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Nim
  • 33,299
  • 2
  • 62
  • 101
  • 1
    Neither is root needed, nor is SIOCGIFCONF a timely interface. Avoid. – user562374 Jan 24 '11 at 11:50
  • stracing `ip addr` shows it using netlink sockets; and, of course, `/bin/ip` is not setuid :) – bdonlan Jan 24 '11 at 11:53
  • @user562374, I did say "I believe", not "it requires", the last time I did this was almost four years ago (but that was for capturing packets off of the interfaces - which did require root - hence the misconception), also, it is a valid mechanism for querying all interfaces on a box, it's not deprecated(?) so what's wrong with it? – Nim Jan 24 '11 at 13:07
  • SIGCGIFCONF won't return ipv6 addresses - and with the IANA pool depleted this is going to be a very important concern soon – bdonlan Jan 24 '11 at 14:10
  • @bdonlan, very true, definitely netlink if you've got ipv6 in your setup (but I'd hazard that most likely the OP's is on a private network, which is ipv4...) I've yet to encounter a private network that is using ipv6 though... – Nim Jan 24 '11 at 14:34