To get IP Address from interface name in Windows

5.5k views Asked by At

I like to know, winapi from which i can get ipaddress using interface name. The Linux version of which is as below.

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <unistd.h>
#include <arpa/inet.h>
int main()
{
    int fd;
    struct ifreq ifr;
    char iface[] = "eth0";
    fd = socket(AF_INET, SOCK_DGRAM, 0);
    //Type of address to retrieve - IPv4 IP address
    ifr.ifr_addr.sa_family = AF_INET;
    //Copy the interface name in the ifreq structure
    strncpy(ifr.ifr_name , iface , IFNAMSIZ-1);
    ioctl(fd, SIOCGIFADDR, &ifr);
    close(fd);
    //display result
    printf("%s - %s\n" , iface , inet_ntoa(( (struct sockaddr_in *)&ifr.ifr_addr )->sin_addr) );
    return 0;
}

I am looking similar functionality ( as code above) but for windows in C++.

4

There are 4 answers

0
westwood On

You have to initialize WinSock first, and only then use gethostname, gethostbyname and inet_ntoa functions. The following link will help you.

0
bytemaster On

SIGAR is a cross-platform library for getting system info (CPU, RAM, DISK, and Network). It will allow you to list all network interfaces on Mac / Windows / Linux and get any other info you may need.

http://support.hyperic.com/display/SIGAR/Home

If you don't want to use the whole library, I am sure you could inspect the code to find just the piece you need.

1
asit_dhal On
0
Dmytro Ovdiienko On

See sample of GetAdaptersAddresses function. FriendlyName and FirstUnicastAddress are fields you need.

http://msdn.microsoft.com/en-us/library/windows/desktop/aa365915%28v=vs.85%29.aspx

See also: Get network interface name from IPv4 address