ubuntu获取本地IP地址

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;
}


你可能感兴趣的:(ubuntu获取本地IP地址)