linux获取网络信息函数

时间:2023-03-09 05:35:37
linux获取网络信息函数

获取IP地址

int sys_getIP(char *ip_addr)
{
  char ip_sys[] = {"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)) !=)
  {
    fprintf(stderr, "[get_eth] ip_sys : 0x%x\n", error_sys);
  }
  if ((ip_fp=fopen("ipaddr.txt", "r")) != NULL)
  {
    fgets(ip_addr, , ip_fp);
  }
  else
  {
    perror ("fread");
    return -;
  }
  fclose (ip_fp);
  unlink("ipaddr.txt");
  return ;
}

获取子网掩码

int sys_getMask(char *mask_addr)
{
  char ip_sys[] = {"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)) !=)
  {
    fprintf(stderr, "[get_eth] ip_sys : 0x%x\n", error_sys);
  }
  if ((ip_fp=fopen("/tmp/ipaddr.txt", "r")) != NULL)
  {
    fgets(mask_addr, , ip_fp);
  }
  else
  {
  perror ("fread");
  return -;
  }
  fclose (ip_fp);
  unlink("/tmp/ipaddr.txt");
  return ; }

获取网关

int sys_getGW(char *gw_addr)
{
  FILE *fp;
  char buf[];
  char cmd[];
  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")) == )
    break;
  }
  sscanf(buf,"%*s%*s%s", gw_addr);
  printf("default gateway:%s\n", gw_addr);
  pclose(fp);
  return ;
}
获取mac地址
int sys_getHW(char *hw_addr)
{
char ip_sys[] = {"ifconfig | sed -e '/.*HWaddr /!d;s///;s/ .*//' > hwaddr.txt"};
FILE *ip_fp = NULL;
int error_sys;
if((error_sys = system(ip_sys)) !=)
{
fprintf(stderr, "[get_eth] ip_sys : 0x%x\n", error_sys);
}
if ((ip_fp=fopen("hwaddr.txt", "r")) != NULL)
{
fgets(hw_addr, , ip_fp);
}
else
{
perror ("fread");
return -;
}
fclose (ip_fp);
unlink("hwaddr.txt");
return ;
}