现在的位置: 首页 > 操作系统 > 正文

ubuntu获取本地IP地址

2018年07月14日 操作系统 ⁄ 共 633字 ⁄ 字号 评论关闭
bool getLocalHostAddr(std::string &ip)
{
	int sockfd;
	struct ifreq req;
	struct sockaddr_in *host;
	char buf[16] = {0};

	if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1)
	{
		cerr << "getLocalHostAddr: Creat socket has error..." << currentDateTime() << endl;
		return false;
	}

	bzero(&req, sizeof(struct ifreq));
	strcpy(req.ifr_name, "eth0");
	if (ioctl(sockfd, SIOCGIFADDR, &req) == -1)
	{
		cerr << "getLocalHostAddr: ioctl has error..." << currentDateTime() << endl;
		return false;
	}

	host = (struct sockaddr_in *)&req.ifr_addr;
	strcpy(buf, inet_ntoa(host->sin_addr));

	close(sockfd);

	stringstream ss;
	ss << buf;

	istringstream iss(ss.str());
	iss >> ip;

	cout << "getLocalHostAddr: " << ip << "	" << currentDateTime() << endl;

	return true;
}

抱歉!评论已关闭.