欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Linux---QT或C语言通过网卡名获取网卡IP和MAC地址

程序员文章站 2022-06-03 08:46:24
...

1. Qt,主要通过#include <QNetworkInterface>这个接口获取的:

QString RuntimeConfig::ipAddress(QString network)
{
    QList<QNetworkAddressEntry> list;
    QString localIPaddress;

    QNetworkInterface interface = QNetworkInterface::interfaceFromName(network);
    list = interface.addressEntries();
    if (!list.isEmpty())
    {
        localIPaddress = list.at(0).ip().toString();
    }

    return localIPaddress;
}

QString RuntimeConfig::macAddress(QString network)
{
    QList<QNetworkInterface> netList;
    int netCount;
    int neti;
    QNetworkInterface myNet;
    netList = QNetworkInterface::allInterfaces();
    netCount = netList.count();

    for (neti = 0; neti < netCount; neti ++)
    {
        if (netList.at(neti).isValid() && netList.at(neti).name() == network)
        {
            myNet = netList.at(neti);
            break;
        }
    }
    return (myNet.hardwareAddress());
}

2. C语言:

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <arpa/inet.h>
#include <errno.h>


int getip(char *ip, char *name)
{
    int sock;
    struct sockaddr_in sin;
    struct ifreq ifr;
    sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock == -1)
    {
        perror("socket");
        return -1;
    }
    strncpy(ifr.ifr_name, name, IFNAMSIZ);
    ifr.ifr_name[IFNAMSIZ - 1] = 0;
    if (ioctl(sock, SIOCGIFADDR, &ifr) < 0)
    {
        perror("ioctl");
        return -1;
    }
    memcpy(&sin, &ifr.ifr_addr, sizeof(sin));
    sprintf(ip, "%s", inet_ntoa(sin.sin_addr));
    return 0;
}

int getmac(char *mac, char *name)
{
    struct ifreq ifreq;
    int   sock;

    if((sock=socket(AF_INET,SOCK_STREAM,0)) <0)
    {
        perror( "socket ");
        return   2;
    }
    strcpy(ifreq.ifr_name, name);
    if(ioctl(sock,SIOCGIFHWADDR,&ifreq) <0)
    {
        perror( "ioctl ");
        return   3;
    }
    sprintf(mac, "%02x:%02x:%02x:%02x:%02x:%02x",
            (unsigned char)ifreq.ifr_hwaddr.sa_data[0],
            (unsigned char)ifreq.ifr_hwaddr.sa_data[1],
            (unsigned char)ifreq.ifr_hwaddr.sa_data[2],
            (unsigned char)ifreq.ifr_hwaddr.sa_data[3],
            (unsigned char)ifreq.ifr_hwaddr.sa_data[4],
            (unsigned char)ifreq.ifr_hwaddr.sa_data[5]);
    return 0;
}

 

 

转自博客园Qt罗:https://www.cnblogs.com/luoxiang/p/4826470.html

相关标签: C/C++ Linux