1、QT下
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> #include "getinfo.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; }
时间: 2024-11-10 11:09:57