获取linux机器的IP和mac地址
2019-07-12 21:45发布
生成海报
#include // for ::strncpy
#include // for ::ioctl
#include // for inet_ntoa
#include // for struct ifreq
#include // for ::close
#include
#include
#include
using namespace std;
int GetNetDeviceAddress(int fd, const char* netDevice, struct in_addr* addr);
vector getNetDevName()
{
vector 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 getLocalIpAddress()
{
vector ipAddrs;
vector netdevs = getNetDevName();
if (netdevs.size() <= 0) {
return ipAddrs;
}
for(size_t i=0; i 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 getLocalMacAddress()
{
vector macAddrs;
vector netdevs = getNetDevName();
if (netdevs.size() <= 0) {
return macAddrs;
}
for(size_t i=0; i 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]< ips = getLocalIpAddress();
vector macs = getLocalMacAddress();
cout << "IP:"<
打开微信“扫一扫”,打开网页后点击屏幕右上角分享按钮