#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 );
}
c語言獲取本機IP及通過pid獲取進程名稱
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.