LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Getting Network Interface Information (http://www.linuxquestions.org/questions/programming-9/getting-network-interface-information-34871/)

yrraja 11-07-2002 10:55 PM

Getting Network Interface Information
 
I am using Redhat Linux 7.2 and C programming language. I want to know two things:

1. How to get the list of Network interfaces the system has?

2. How to get the IP addresses (IPv4/IPv6) associated with each interface?

any comments on this will be appreciated..

leed_25 11-07-2002 11:10 PM

ifconfig -a

yrraja 11-08-2002 02:23 AM

Thanx leed_25 but i want some function call which does this within my C program. I dont want to use the system call and parsing.

Mik 11-08-2002 03:16 AM

Well you can read the information directly from the proc filesystem. But the proc filesystem isn't always present and you will have to write a parser for the information which isn't always convenient.

There are other ways to get information using ioctls. You should read the following manpage: 'man 7 netdevice'

Mik 11-08-2002 05:02 AM

Well since I was curious on how it actually worked, I wrote a small program which gets a list of all the interfaces and their ip numbers. Well here is the source code:

Code:

#include <sys/ioctl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <net/if.h>

int main()
{
  struct ifconf conf;
  struct sockaddr_in *s_in;
  int sock, i, count;

  // Open dummy socket
  if ((sock = socket(PF_INET, SOCK_DGRAM, 0)) == -1)
  {
    perror("error opening socket");
    return -1;
  }

  // Get list of devices (only gets first 10)
  memset(&conf, 0, sizeof(conf));
  conf.ifc_len = sizeof(struct ifreq) * 10;
  conf.ifc_buf = (char*) malloc(conf.ifc_len);
       
  if (ioctl(sock, SIOCGIFCONF, &conf) == -1)
  {
    perror("failed to get device list");
    return -1;
  }

  count = conf.ifc_len / sizeof(struct ifreq);

  for (i = 0; i < count; i++)
  {
    s_in = (struct sockaddr_in*) &conf.ifc_req[i].ifr_addr;
    printf("%s %s\n", conf.ifc_req[i].ifr_name,
                      inet_ntoa(s_in->sin_addr));
  }

  free(conf.ifc_buf);

  return 0;
}


yrraja 11-10-2002 11:46 PM

Thanx for the code Nik. It was great help.


All times are GMT -5. The time now is 06:58 AM.