嵌入式linux获取网络IP和子网掩码

2019-07-13 00:34发布

int GetIPAddrAndNetMask(char *ps8Ipaddr, char *ps8NetMask, const char *ps8IfName)
{
 int sock;
 struct sockaddr_in *sin;
 struct ifreq *ifr;
 char as8Buff[BUFSIZ];
 struct ifconf conf;  if ( ( sock = socket(AF_INET, SOCK_DGRAM, 0) ) < 0)
 {
  perror("socket");
  return -1;
 }  conf.ifc_len = BUFSIZ;
 conf.ifc_buf = as8Buff;
 if( ioctl( sock, SIOCGIFCONF, &conf) == -1 )
 {
  close( sock );
  return -1;
 }  int s32Num = conf.ifc_len / sizeof(struct ifreq);
 ifr = conf.ifc_req;  for (int i = 0; i < s32Num; i++ )
 {
  sin = (struct sockaddr_in *)(&ifr->ifr_addr );
  if ( ioctl( sock, SIOCGIFFLAGS, ifr) == -1 )
  {
   close( sock );
   return -1;
  }   if ( ((ifr->ifr_flags & IFF_LOOPBACK) == 0) &&
    (ifr->ifr_flags & IFF_UP) &&
    (strcmp(ifr->ifr_name, ps8IfName) == 0) )
  {
   ps8Ipaddr[0] = (sin->sin_addr.s_addr)       & 0xFF;
   ps8Ipaddr[1] = (sin->sin_addr.s_addr) >> 8  & 0xFF;
   ps8Ipaddr[2] = (sin->sin_addr.s_addr) >> 16 & 0xFF;
   ps8Ipaddr[3] = (sin->sin_addr.s_addr) >> 24 & 0xFF;
  }
  ifr++;
 }
  if ( ps8NetMask )
 {
  sin = (struct sockaddr_in *)(&ifr->ifr_addr);
  strcpy(ifr->ifr_name, ps8IfName);
  if ( ioctl( sock, SIOCGIFNETMASK, ifr ) == -1 )
  {
   close( sock );
   return -1;
  }   ps8NetMask[0] = (sin->sin_addr.s_addr)       & 0xFF;
  ps8NetMask[1] = (sin->sin_addr.s_addr) >> 8  & 0xFF;
  ps8NetMask[2] = (sin->sin_addr.s_addr) >> 16 & 0xFF;
  ps8NetMask[3] = (sin->sin_addr.s_addr) >> 24 & 0xFF;    }
 close(sock);
 return 0;
}