This question is exactly like this question: How to get MAC address of your machine using a C program?
"I am working on Ubuntu. How can I get MAC address of my machine or an interface say eth0 using C program."
Now, I don't usually touch C...but in this case I have to. Since I don't really know what is going on in the following code, which was taken from the answer linked to above, I need some help.
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <linux/if.h>
#include <netdb.h>
#include <stdio.h>
int main()
{
struct ifreq s;
int fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
strcpy(s.ifr_name, "eth0");
if (0 == ioctl(fd, SIOCGIFHWADDR, &s)) {
int i;
for (i = 0; i < 6; ++i)
printf(" %02x", (unsigned char) s.ifr_addr.sa_data[i]);
puts("\n");
return 0;
}
return 1;
}
Instead of a function that prints the MAC Address I need a function that returns it as a string. You know, like this:
const char * gettaStringFromNativeCode(void)
{
return "This is a string";
}
This is to be used with Mozilla Chromeless, which uses Firefox's new JCTYPES like this.
Basically, I'm looking to do something like this (borrowing from C#):
// Using "string" here because its pseudo-code and I don't know what i'm doing. :-)
string getMAC()
{
struct ifreq s;
int fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
strcpy(s.ifr_name, "eth0");
var macAddress = string.Empty; // yah, this is actually C#
if (0 == ioctl(fd, SIOCGIFHWADDR, &s)) {
int i;
for (i = 0; i < 6; ++i)
// yah, this is a bit of C# too.
macAddress += string.Format(" %02x", (unsigned char) s.ifr_addr.sa_data[i]) );
}
return macAddress;
}