linux获取网络信息函数

来源:互联网 发布:原装ubuntu的电脑 编辑:程序博客网 时间:2024/05/19 01:07

获取IP地址
int sys_getIP(char *ip_addr)
{
char ip_sys[80] =
{“ifconfig eth0 | grep inet | cut -d: -f2 | cut -d’ ’ -f1 > ipaddr.txt”};
FILE *ip_fp = NULL;
int error_sys;
if((error_sys = system(ip_sys)) !=0)
{
fprintf(stderr, “[get_eth] ip_sys : 0x%x\n”, error_sys);
}
if ((ip_fp=fopen(“ipaddr.txt”, “r”)) != NULL)
{
fgets(ip_addr, 39, ip_fp);
}
else
{
perror (“fread”);
return -1;
}
fclose (ip_fp);
unlink(“ipaddr.txt”);
return 0;
}
获取子网掩码
int sys_getMask(char *mask_addr)
{
char ip_sys[80] =
{“ifconfig eth0 | grep Mask | cut -dk -f2 | cut -d: -f2 > /tmp/ipaddr.txt”};
FILE *ip_fp = NULL;
int error_sys;
if((error_sys = system(ip_sys)) !=0)
{
fprintf(stderr, “[get_eth] ip_sys : 0x%x\n”, error_sys);
}
if ((ip_fp=fopen(“/tmp/ipaddr.txt”, “r”)) != NULL)
{
fgets(mask_addr, 39, ip_fp);
}
else
{
perror (“fread”);
return -1;
}
fclose (ip_fp);
unlink(“/tmp/ipaddr.txt”);
return 0;

}
获取网关
int sys_getGW(char *gw_addr)
{
FILE *fp;
char buf[512];
char cmd[128];
char *tmp;
strcpy(cmd, “ip route”);
fp = popen(cmd, “r”);
if(NULL == fp)
{
perror(“popen error”);
return “”;
}
while(fgets(buf, sizeof(buf), fp) != NULL) //stroe output one line!!
{
tmp =buf;
while(*tmp && isspace(*tmp))
++ tmp;
if(strncmp(tmp, “default”, strlen(“default”)) == 0)
break;
}
sscanf(buf,”%*s%*s%s”, gw_addr);
printf(“default gateway:%s\n”, gw_addr);
pclose(fp);
return 0;
}
获取mac地址
int sys_getHW(char *hw_addr)
{
char ip_sys[80] =
{“ifconfig | sed -e ‘/.HWaddr /!d;s///;s/ .//’ > hwaddr.txt”};
FILE *ip_fp = NULL;
int error_sys;
if((error_sys = system(ip_sys)) !=0)
{
fprintf(stderr, “[get_eth] ip_sys : 0x%x\n”, error_sys);
}
if ((ip_fp=fopen(“hwaddr.txt”, “r”)) != NULL)
{
fgets(hw_addr, 39, ip_fp);
}
else
{
perror (“fread”);
return -1;
}
fclose (ip_fp);
unlink(“hwaddr.txt”);
return 0;
}

原创粉丝点击