5

Possible Duplicate:
Linux / C++: Get the IP Address of local computer

I am trying to get my local computer's IP and MAC addresses of all interfaces, but I can not really succeed. I need to get it together, so I know which IP belongs to which MAC.

I went through a lot of searching on google and even here, but I can not really find a C code for this.

Could you please help me?

Thanks in advance! I would really appreciate that!

Community
  • 1
  • 1
shaggy
  • 631
  • 4
  • 11
  • 22
  • not duplicate, `getifaddrs()` does not work with HW address, just IP – shaggy Jul 20 '11 at 19:33
  • OK, possibly not exact, but combination of my first link and [this one](http://stackoverflow.com/questions/1779715/how-to-get-mac-address-of-your-machine-using-a-c-program) should get you want you need. – Peter K. Jul 20 '11 at 19:48
  • I have already tried the second one, but it contains too many errors, I ve tried to fix it up, but I couldnt really fix all the errors. – shaggy Jul 20 '11 at 19:50

4 Answers4

9

On relatively recent versions of Linux, you can just read the contents of /sys/class/net/eth0/address (substituting any network interface name for eth0) to get the hardware address of an interface.

bitbucket
  • 1,307
  • 7
  • 11
  • 2
    does the sys directory contain the current ip address for the interface as well? –  Oct 07 '17 at 20:05
7

Just found this to be working:

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <stdio.h>
#include <string.h>

void mac_eth0(unsigned char MAC_str[13])
{
    #define HWADDR_len 6
    int s,i;
    struct ifreq ifr;
    s = socket(AF_INET, SOCK_DGRAM, 0);
    strcpy(ifr.ifr_name, "eth0");
    ioctl(s, SIOCGIFHWADDR, &ifr);
    for (i=0; i<HWADDR_len; i++)
        sprintf(&MAC_str[i*2],"%02X",((unsigned char*)ifr.ifr_hwaddr.sa_data)[i]);
    MAC_str[12]='\0';
    close(s);
}

int main(int argc, char *argv[])
{
    unsigned char mac[13];

    mac_eth0(mac);
    puts(mac);

    return 0;
}
RatDon
  • 3,403
  • 8
  • 43
  • 85
Friek
  • 1,533
  • 11
  • 13
  • Oops, I just read you need the IP as well. For a portable way of getting IP addresses from an interface, I suggest using libpcap. – Friek Jul 20 '11 at 19:43
2

You can get the MAC address using the SIOCGIFADDR ioctl.

A full example can be found here.

John Slegers
  • 45,213
  • 22
  • 199
  • 169
kcbanner
  • 4,050
  • 1
  • 25
  • 18
  • The first link is now broken, it could be better to include the essential part of the second link in your answer. – mpromonet Feb 06 '16 at 15:18
1

On your local computer? Since it is tagged under linux, open a terminal, and type ifconfig -a. That displays all the info on all interfaces On your local network, your IP is listed under inet address.The HWaddr is the MAC address. For external IP, you'll have to use a script to fetch it.

EDIT : Click Here for using it for a C Program

Community
  • 1
  • 1
Aaditi Sharma
  • 766
  • 2
  • 9
  • 20