bool NetClient::GetIpByIf(const std::string& ifname, std::string* ip) {
if (ifname.empty() || ip == NULL) {
return false;
}
int fd, intrface;
struct ifreq buf[10];
struct ifconf ifc = {0, {0}};
memset(buf, 0, sizeof(buf));
struct in_addr addr;
char addr_buffer[32] = {0};
if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) >= 0) {
ifc.ifc_len = sizeof(buf);
ifc.ifc_buf = (caddr_t)buf;
if (!ioctl(fd, SIOCGIFCONF, &ifc)) {
intrface = ifc.ifc_len / sizeof(struct ifreq);
while (intrface-- > 0) {
if (strcmp(buf[intrface].ifr_name, ifname.c_str()) == 0) {
if (!(ioctl(fd, SIOCGIFADDR, &buf[intrface]))) {
memset(addr_buffer, 0, sizeof(addr_buffer));
addr = ((struct sockaddr_in*)(&buf[intrface].ifr_addr))->sin_addr;
if (inet_ntop(AF_INET, static_cast<void*>(&addr), addr_buffer, sizeof(addr_buffer))) {
ip->assign(addr_buffer);
close(fd);
return true;
}
}
break;
}
}
}
close(fd);
}
return false;
}
评论