Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I output my host’s IP addresses from a C program?

Tags:

c

linux

sockets

ip

I need to display all the IP addresses from my local computer, using the C language. How can this be done?

like image 748
Emanuel Avatar asked Jan 07 '10 15:01

Emanuel


People also ask

How do I find my host C IP address?

Here is a simple method to find hostname and IP address using C program. gethostname() : The gethostname function retrieves the standard host name for the local computer. gethostbyname() : The gethostbyname function retrieves host information corresponding to a host name from a host database.

Which methods you will use to get the IP address of your system?

First, click on your Start Menu and type cmd in the search box and press enter. A black and white window will open where you will type ipconfig /all and press enter. There is a space between the command ipconfig and the switch of /all. Your ip address will be the IPv4 address.


2 Answers

#include <stdio.h>
#include <stropts.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <linux/netdevice.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>

int print_addresses(const int domain)
{
  int s;
  struct ifconf ifconf;
  struct ifreq ifr[50];
  int ifs;
  int i;

  s = socket(domain, SOCK_STREAM, 0);
  if (s < 0) {
    perror("socket");
    return 0;
  }

  ifconf.ifc_buf = (char *) ifr;
  ifconf.ifc_len = sizeof ifr;

  if (ioctl(s, SIOCGIFCONF, &ifconf) == -1) {
    perror("ioctl");
    return 0;
  }

  ifs = ifconf.ifc_len / sizeof(ifr[0]);
  printf("interfaces = %d:\n", ifs);
  for (i = 0; i < ifs; i++) {
    char ip[INET_ADDRSTRLEN];
    struct sockaddr_in *s_in = (struct sockaddr_in *) &ifr[i].ifr_addr;

    if (!inet_ntop(domain, &s_in->sin_addr, ip, sizeof(ip))) {
      perror("inet_ntop");
      return 0;
    }

    printf("%s - %s\n", ifr[i].ifr_name, ip);
  }

  close(s);

  return 1;
}

int main(int argc, char *argv[])
{
  int domains[] = { AF_INET, AF_INET6 };
  int i;

  for (i = 0; i < sizeof(domains) / sizeof(domains[0]); i++)
    if (!print_addresses(domains[i]))
      return 1;

  return 0;
}
like image 76
Greg Bacon Avatar answered Sep 21 '22 20:09

Greg Bacon


Your question might be imprecise but I am not sure why everyone is breaking your chops.

I think you are asking the basics in which case you probably want is getifaddrs. The man page has a little example program.

You can also get similar info using the SIOCGIFCONF option with ioctl(). There is some sample code on here and the web.

If you search around for these and similar terms you will find this question has been asked in various forms before. You have to dig around a bit.

Also note, these will not give you the public facing IP of your network if you are behind NAT.

like image 25
Duck Avatar answered Sep 20 '22 20:09

Duck