linux下获取本机ip代码

#include <iostream>
#include <string.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <linux/if.h>

using namespace std;

int GetLocalIP(char* outip);

int main()
{
	char ip[20];
	int ret = GetLocalIP(ip);
	cout<<ip<<endl;
}



int GetLocalIP(char* outip)
{
	int sockfd;
	struct ifconf ifconf;
	char buf[512];
	struct ifreq *ifreq;
	char* ip;

	ifconf.ifc_len = 512;
	ifconf.ifc_buf = buf;

	if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
	{
		return -1;
	}

	ioctl(sockfd, SIOCGIFCONF, &ifconf);
	close(sockfd);

	ifreq = (struct ifreq*)buf;
	for (int i = (ifconf.ifc_len / sizeof(struct ifreq)); i > 0; i--)
	{
		ip = inet_ntoa(((struct sockaddr_in*)&(ifreq->ifr_addr))->sin_addr);
		if(strcmp(ip, "127.0.0.1") == 0) 
		{
			ifreq++;
			continue;
		}

		strcpy(outip, ip);
		return 0;
	}

	return -1;
}

你可能感兴趣的:(linux下获取本机ip代码)