Reputation: 45
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.
Upvotes: 3
Views: 7283
Reputation: 7804
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
Upvotes: -2
Reputation: 595887
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.
Upvotes: 8