c语言获取本机IP及通过pid获取进程名称

#include<stdio.h>
#include <stdlib.h>
#include<time.h>
#include <ifaddrs.h>
#include <sys/socket.h>
#include <netdb.h>

/*获取本机IP*/
int gethostip(char *hostip);

/*通过pid获取进程名*/
int getnamebypid(int pid,char *pname);

int main() 
{
	char ch_hostip[64];
	char ch_pname[128];
	
	memset(ch_hostip,0,sizeof(ch_hostip));
	memset(ch_pname,0,sizeof(ch_pname));
	
	gethostip(ch_hostip);
	printf("ch_hostip=[%s]\n",ch_hostip);
	
	/*18782为测试的pid*/
	getnamebypid(18782,ch_pname);
	printf("ch_pname=[%s]\n",ch_pname);
	
	return 0;

}

int gethostip(char *hostip)
{
	struct ifaddrs *ifaddr, *ifa;
	int family, s;
	char *host = NULL;
 
	if (getifaddrs(&ifaddr) == -1) 
	{
		return ( -1 );
	}
 
	for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
		if (ifa->ifa_addr == NULL)
			continue;
 
		family = ifa->ifa_addr->sa_family;
 
		if (!strcmp(ifa->ifa_name, "lo"))
			continue;
		if (family == AF_INET) 
		{
			s = getnameinfo(ifa->ifa_addr,
					(family == AF_INET) ? sizeof(struct sockaddr_in) :
					sizeof(struct sockaddr_in6),
					hostip, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
			if (s != 0)
			{
				return ( -1 );
			}
			freeifaddrs(ifaddr);
			return ( 0 );
		}
	}
	return ( -1 );
}

int getnamebypid(int pid,char *pname)
{
	char ch_fullpath[1024+1];
	char ch_line[1024+1];
	FILE *fp;
	
	memset(ch_fullpath,0,sizeof(ch_fullpath));
	memset(ch_line,0,sizeof(ch_line));
	
	sprintf(ch_fullpath,"/proc/%d/status",pid);
	
	fp = fopen(ch_fullpath,"r");
	if (NULL != fp)
	{
		fgets(ch_line, sizeof(ch_line), fp);
		sscanf(ch_line, "%*s %s", pname);
		fclose(fp);
	}
	
	return ( 0 );
}

猜你喜欢

转载自blog.csdn.net/woailp___2005/article/details/103314219
今日推荐