C Code to get MAC Address and IP Address

This is cool. But then the author has plenty of solid information on his blog.

vienergie

Function in C to return the MAC Address:

/* Returns the MAC Address
   Params: int iNetType - 0: ethernet, 1: Wifi
           char chMAC[6] - MAC Address in binary format
   Returns: 0: success
           -1: Failure
    */
int getMACAddress(int iNetType, char chMAC[6]) {
  struct ifreq ifr;
  int sock;
  char *ifname=NULL;

  if (!iNetType) {
    ifname="eth0"; /* Ethernet */
  } else {
    ifname="wlan0"; /* Wifi */
  }
  sock=socket(AF_INET,SOCK_DGRAM,0);
  strcpy( ifr.ifr_name, ifname );
  ifr.ifr_addr.sa_family = AF_INET;
  if (ioctl( sock, SIOCGIFHWADDR, &ifr ) < 0) {
    return -1;
  }
  memcpy(chMAC, ifr.ifr_hwaddr.sa_data, 6)
  close(sock);
  return 0;
}

Function in C to return the IP Address:

/* Returns the interface IP Address Params: int iNetType - 0: ethernet, 1: Wifi char *chIP - IP Address string Return: 0: success / -1: Failure */ int getIpAddress(int iNetType, char chIP[16]) { struct ifreq ifr; int sock = 0; sock = socket(AF_INET, SOCK_DGRAM, 0); if(iNetType == 0) { strcpy(ifr.ifr_name, "eth0")…

View original post 29 more words

This entry was posted in Brian By Experience, Brian's Code Extreme, C-Langs and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.