Frage

Ich arbeite an Ubuntu. Wie kann ich die MAC-Adresse meiner Maschine oder eine Schnittstelle sagen eth0 mit C-Programm erhalten.

War es hilfreich?

Lösung

Sie müssen Iterierte über alle verfügbaren Schnittstellen auf Ihrem Computer und die Verwendung ioctl mit SIOCGIFHWADDR Fahne, um die MAC-Adresse zu erhalten. Die MAC-Adresse wird als 6-Oktett binäres Array erhalten werden. Sie wollen auch die Loopback-Schnittstelle überspringen.

#include <sys/ioctl.h>
#include <net/if.h> 
#include <unistd.h>
#include <netinet/in.h>
#include <string.h>

int main()
{
    struct ifreq ifr;
    struct ifconf ifc;
    char buf[1024];
    int success = 0;

    int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
    if (sock == -1) { /* handle error*/ };

    ifc.ifc_len = sizeof(buf);
    ifc.ifc_buf = buf;
    if (ioctl(sock, SIOCGIFCONF, &ifc) == -1) { /* handle error */ }

    struct ifreq* it = ifc.ifc_req;
    const struct ifreq* const end = it + (ifc.ifc_len / sizeof(struct ifreq));

    for (; it != end; ++it) {
        strcpy(ifr.ifr_name, it->ifr_name);
        if (ioctl(sock, SIOCGIFFLAGS, &ifr) == 0) {
            if (! (ifr.ifr_flags & IFF_LOOPBACK)) { // don't count loopback
                if (ioctl(sock, SIOCGIFHWADDR, &ifr) == 0) {
                    success = 1;
                    break;
                }
            }
        }
        else { /* handle error */ }
    }

    unsigned char mac_address[6];

    if (success) memcpy(mac_address, ifr.ifr_hwaddr.sa_data, 6);
}

Andere Tipps

Viel schöner als alle diese Buchse oder Shell-Wahnsinn ist einfach sysfs für diese Verwendung:

die Datei /sys/class/net/eth0/address trägt Ihre Mac-Adresse als einfache Zeichenfolge, die Sie mit fopen() / fscanf() / fclose() lesen können. Nichts leichter als das.

Und wenn Sie andere Netzwerkschnittstellen als eth0 unterstützen wollen (und Sie wollen wahrscheinlich), dann verwenden Sie einfach opendir() / readdir() / closedir() auf /sys/class/net/.

Sie möchten einen Blick auf, der getifaddrs (3) Handbuch Seite. Es gibt ein Beispiel in C in der Manual-Page selbst, dass Sie verwenden können. Sie wollen die Adresse mit dem Typ AF_LINK erhalten.

#include <sys/socket.h>
#include <sys/ioctl.h>
#include <linux/if.h>
#include <netdb.h>
#include <stdio.h>
#include <string.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;
}

Mit getifaddrs MAC-Adresse aus dem bekommen Familie AF_PACKET.

Um jede Schnittstelle die MAC-Adresse angezeigt werden, können Sie wie folgt vorgehen:

#include <stdio.h>
#include <ifaddrs.h>
#include <netpacket/packet.h>

int main (int argc, const char * argv[])
{
    struct ifaddrs *ifaddr=NULL;
    struct ifaddrs *ifa = NULL;
    int i = 0;

    if (getifaddrs(&ifaddr) == -1)
    {
         perror("getifaddrs");
    }
    else
    {
         for ( ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next)
         {
             if ( (ifa->ifa_addr) && (ifa->ifa_addr->sa_family == AF_PACKET) )
             {
                  struct sockaddr_ll *s = (struct sockaddr_ll*)ifa->ifa_addr;
                  printf("%-8s ", ifa->ifa_name);
                  for (i=0; i <s->sll_halen; i++)
                  {
                      printf("%02x%c", (s->sll_addr[i]), (i+1!=s->sll_halen)?':':'\n');
                  }
             }
         }
         freeifaddrs(ifaddr);
    }
    return 0;
}

Ideone

Ich habe nur schreiben ein und testen Sie es auf gentoo in VirtualBox.

// get_mac.c
#include <stdio.h>    //printf
#include <string.h>   //strncpy
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>   //ifreq
#include <unistd.h>   //close

int main()
{
    int fd;
    struct ifreq ifr;
    char *iface = "enp0s3";
    unsigned char *mac = NULL;

    memset(&ifr, 0, sizeof(ifr));

    fd = socket(AF_INET, SOCK_DGRAM, 0);

    ifr.ifr_addr.sa_family = AF_INET;
    strncpy(ifr.ifr_name , iface , IFNAMSIZ-1);

    if (0 == ioctl(fd, SIOCGIFHWADDR, &ifr)) {
        mac = (unsigned char *)ifr.ifr_hwaddr.sa_data;

        //display mac address
        printf("Mac : %.2X:%.2X:%.2X:%.2X:%.2X:%.2X\n" , mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
    }

    close(fd);

    return 0;
}

Unter der Annahme, dass die C ++ Code (C ++ 11) als auch in Ordnung, und die Schnittstelle bekannt ist.

#include <cstdint>
#include <fstream>
#include <streambuf>
#include <regex>

using namespace std;

uint64_t getIFMAC(const string &ifname) {
  ifstream iface("/sys/class/net/"+ifname+"/address");
  string str((istreambuf_iterator<char>(iface)), istreambuf_iterator<char>());
  if (str.length() > 0) {
    string hex = regex_replace(str, std::regex(":"), "");
    return stoull(hex, 0, 16);
  } else {
    return 0;
  }
} 
int main()
{
  string iface="eth0";
  printf("%s: mac=%016lX\n", iface.c_str(), getIFMAC(iface));
}
  1. Unter Linux nutzt den Service von "Network Manager" über den D-Bus.

  2. Es gibt auch good'ol Shell-Programm, das invoke sein kann und das Ergebnis packte (verwenden Sie eine exec Funktion unter C):

$ /sbin/ifconfig | grep HWaddr

Eine sehr tragbare Art und Weise ist die Ausgabe dieses Befehls zu analysieren.

ifconfig | awk '$0 ~ /HWaddr/ { print $5 }'

Sofern ifconfig kann als der aktuelle Benutzer ausgeführt werden (in der Regel kann) und awk installiert ist (es oft ist). Dies gibt Ihnen die MAC-Adresse der Maschine.

Dies ist eine Bash Linie, die alle verfügbaren MAC-Adressen druckt, mit Ausnahme des Loopback:

for x in `ls /sys/class/net |grep -v lo`; do cat /sys/class/net/$x/address; done

Kann aus einem C-Programm ausgeführt werden.

Aufbauend auf der Antwort von @ user175104 ...

std::vector<std::string> GetAllFiles(const std::string& folder, bool recursive = false)
{
  // uses opendir, readdir, and struct dirent.
  // left as an exercise to the reader, as it isn't the point of this OP and answer.
}

bool ReadFileContents(const std::string& folder, const std::string& fname, std::string& contents)
{
  // uses ifstream to read entire contents
  // left as an exercise to the reader, as it isn't the point of this OP and answer.
}

std::vector<std::string> GetAllMacAddresses()
{
  std::vector<std::string> macs;
  std::string address;

  // from: https://stackoverflow.com/questions/9034575/c-c-linux-mac-address-of-all-interfaces
  //  ... just read /sys/class/net/eth0/address

  // NOTE: there may be more than one: /sys/class/net/*/address
  //  (1) so walk /sys/class/net/* to find the names to read the address of.

  std::vector<std::string> nets = GetAllFiles("/sys/class/net/", false);
  for (auto it = nets.begin(); it != nets.end(); ++it)
  {
    // we don't care about the local loopback interface
    if (0 == strcmp((*it).substr(-3).c_str(), "/lo"))
      continue;
    address.clear();
    if (ReadFileContents(*it, "address", address))
    {
      if (!address.empty())
      {
        macs.push_back(address);
      }
    }
  }
  return macs;
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top