Home > Linux, Programming > C Code to get MAC Address and IP Address

C Code to get MAC Address and IP Address

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");
  } else {
    strcpy(ifr.ifr_name, "wlan0");
  }
  if (ioctl(sock, SIOCGIFADDR, &ifr) < 0) {
    strcpy(chIP, "0.0.0.0");
    return -1;
 }
 sprintf(chIP, "%s", inet_ntoa(((struct sockaddr_in *) &(ifr.ifr_addr))->sin_addr));
 close(sock);
 return 0;
}
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter

Categories: Linux, Programming Tags: Linux, c#, networking, programming, socket
  1. No comments yet.
  1. No trackbacks yet.