#include <string.h> // for ::strncpy
#include <sys/ioctl.h> // for ::ioctl
#include <arpa/inet.h> // for inet_ntoa
#include <net/if.h> // for struct ifreq
#include <unistd.h> // for ::close
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
int GetNetDeviceAddress(int fd, const char* netDevice, struct in_addr* addr);
vector<string> getNetDevName()
{
vector<string> result;
ifstream ifs("/proc/net/dev");
string line;
if(ifs) {
while(getline(ifs, line)) {
size_t end = 0;
if ((end = line.find(":")) != string::npos) {
size_t start = line.find_first_not_of(' ');
string name = line.substr(start, end-start);
if (name.compare("lo")) {
result.push_back(name);
}
}
}
}
ifs.close();
return result;
}
vector<string> getLocalIpAddress()
{
vector<string> ipAddrs;
vector<string> netdevs = getNetDevName();
if (netdevs.size() <= 0) {
return ipAddrs;
}
for(size_t i=0; i<netdevs.size(); ++i) {
int sock;
if ((sock = ::socket(AF_INET, SOCK_DGRAM, 0)) > 0) {
struct in_addr addr;
bzero(&addr, sizeof(addr));
if (!(GetNetDeviceAddress(sock, netdevs[i].c_str(), &addr))) {
ipAddrs.push_back(inet_ntoa(addr));
}
::close(sock);
}
}
return ipAddrs;
}
int GetNetDeviceAddress(int fd, const char* netDevice, struct in_addr* addr)
{
struct ifreq req;
::strncpy(req.ifr_name, netDevice, IF_NAMESIZE);
if (::ioctl(fd, SIOCGIFFLAGS, &req) < 0) {
return -1;
}
// Check whether network interface can be accessed
if ((req.ifr_flags & IFF_RUNNING) == 0) {
return -1;
}
// Retrieve binded IP address for the interface
if (::ioctl(fd, SIOCGIFADDR, &req) < 0) {
return -1;
}
else {
::memcpy(addr, &(((struct sockaddr_in*)&req.ifr_addr)->sin_addr), sizeof(struct in_addr));
}
return 0;
}
vector<string> getLocalMacAddress()
{
vector<string> macAddrs;
vector<string> netdevs = getNetDevName();
if (netdevs.size() <= 0) {
return macAddrs;
}
for(size_t i=0; i<netdevs.size(); ++i) {
int sock;
if ((sock = ::socket(AF_INET, SOCK_DGRAM, 0)) > 0) {
struct ifreq ifr_mac;
bzero(&ifr_mac, sizeof(ifr_mac));
::strncpy(ifr_mac.ifr_name, netdevs[i].c_str(), IF_NAMESIZE);
char addr[32] = {0};
if (::ioctl(sock, SIOCGIFHWADDR, &ifr_mac) >= 0) {
snprintf(addr, 32, "%02x:%02x:%02x:%02x:%2x:%2x",
(unsigned char)ifr_mac.ifr_hwaddr.sa_data[0],
(unsigned char)ifr_mac.ifr_hwaddr.sa_data[1],
(unsigned char)ifr_mac.ifr_hwaddr.sa_data[2],
(unsigned char)ifr_mac.ifr_hwaddr.sa_data[3],
(unsigned char)ifr_mac.ifr_hwaddr.sa_data[4],
(unsigned char)ifr_mac.ifr_hwaddr.sa_data[5]);
macAddrs.push_back(addr);
}
else {
cout<<"can not get local mac address for " << netdevs[i]<<endl;
}
::close(sock);
}
}
return macAddrs;
}
int main()
{
vector<string> ips = getLocalIpAddress();
vector<string> macs = getLocalMacAddress();
cout << "IP:"<<endl;
for(size_t i=0; i<ips.size();++i) {
cout << "\t" << ips[i] << endl;
}
cout << endl;
cout << "Mac:"<<endl;
for(size_t i=0; i<macs.size();++i) {
cout << "\t" << macs[i] << endl;
}
return 0;
}
获取linux机器的IP和mac地址
最新推荐文章于 2024-10-14 11:03:08 发布