3

How do I get the IP address of the local machine in C on Windows? I was not able to get the IP address of my machine in the following code:

#include <ifaddrs.h>
#include <stdio.h>

int main()
{
    struct ifaddrs *id;
    int val;
    val = getifaddrs(&id);
    printf("Network Interface Name :- %s\n",id->ifa_name);
    printf("Network Address of %s :- %d\n",id->ifa_name,id->ifa_addr);
    printf("Network Data :- %d \n",id->ifa_data);
    printf("Socket Data : -%c\n",id->ifa_addr->sa_data);
    return 0;
}

I am facing an error while compiling:

fatal error C1083: Cannot open include file: 'net/if.h': No such file or directory.

I cannot use #include <net/if.h> as it is only available on Linux.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Niks Arora
  • 45
  • 1
  • 7
  • 1
    The code above is for Linux and similar operating systems - to do the same thing on Windows you'll need to look at MSDN to find Microsoft's equivalent API. – Paul R Dec 14 '16 at 09:57
  • 2
    Possible duplicate of [How to get the ip address under Windows](http://stackoverflow.com/questions/5114305/how-to-get-the-ip-address-under-windows) – Swanand Dec 14 '16 at 10:00
  • Maybe [this SO question](http://stackoverflow.com/questions/122208/get-the-ip-address-of-local-computer) helps. – Jabberwocky Dec 14 '16 at 10:01
  • swanand that question is using linux code as including net/if.h . – Niks Arora Dec 14 '16 at 10:06

2 Answers2

8

The code you showed does not compile because it is designed for Linux, not Windows. There is no <net/if.h> header on Windows.

getifaddrs() returns a linked list of local interface addresses. But getifaddrs() does not exist on Windows at all (unless you find a custom 3rd party implementation).

The equivalent on Windows is to use the Win32 GetAdaptersInfo() function on XP and earlier, or the GetAdaptersAddresses() function on Vista and later. Both functions return a linked list of detailed adapter information (much more than just addresses).

C examples are provided in their documentation on MSDN.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
-2

The structure

struct ifaddrs *id;

is a linked list. You have to loop through it and check the existence of the address

if(id->fa_addr)
   // print statements
phuclv
  • 37,963
  • 15
  • 156
  • 475
Daksh Gupta
  • 7,554
  • 2
  • 25
  • 36