获取本地ip地址信息

#include<stdio.h>
#include <sys/ioctl.h>
#include<netinet/in.h>
#include<net/if.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string.h>

typedef unsigned short uint16_t;
typedef unsigned int uint32_t;

bool queryLocalIpAddrInfos()
{
  int sock;
  struct sockaddr_in* addr;
  struct ifreq* ifr;
  struct ifconf ifc;
  char buffer[1024];
  const char IFNAME[] = "lo";
  uint16_t pub = 0;
  uint32_t idc = 0;

  sock = socket(AF_INET, SOCK_DGRAM, 0);
  printf("create socket:%d\n",sock);
  if (sock < 0)
  {
    printf("queryLocalIpAddrInfos, fail to create socket");
    return false;
  }

  // get all interface
  ifc.ifc_len = sizeof(buffer);
  ifc.ifc_buf = buffer;
  if (ioctl(sock, SIOCGIFCONF, (char *)&ifc) < 0)
  {
    printf("queryLocalIpAddrInfos, fail to get IF list");
    close(sock);
    return false;
  }
  ifr = ifc.ifc_req;
  printf("loop times:%lu\n",ifc.ifc_len/sizeof(struct ifreq));
  for (int idx = ifc.ifc_len / sizeof(struct ifreq); --idx >= 0; ifr++)
  {
	printf("ifr->ifr_name:%s\n",ifr->ifr_name);  
    // skip 'lo'
    if (!strcmp(ifr->ifr_name, IFNAME))
		continue;
	
    // flags
    if (ioctl(sock, SIOCGIFFLAGS, ifr) == -1)
    {
      printf("queryLocalIpAddrInfos, fail to get flags for interface %s", ifr->ifr_name);
      continue;
    }

    if (ioctl(sock, SIOCGIFADDR, ifr) == -1)
    {
      printf("queryLocalIpAddrInfos, fail to get ip address for interface %s", ifr->ifr_name);
      continue;
    }
    addr = (struct sockaddr_in *)&(ifr->ifr_addr);
    uint32_t m_nLocalIp = addr->sin_addr.s_addr;
	printf("m_nLocalIp:%u\n",m_nLocalIp);

    // network mask
    if (ioctl(sock, SIOCGIFNETMASK, ifr) == -1)
    {
      printf("queryLocalIpAddrInfos, fail to get network mask for interface %s", ifr->ifr_name);
      continue;
    }
    addr = (struct sockaddr_in *)&(ifr->ifr_addr);
    uint32_t  m_nNetMask = addr->sin_addr.s_addr;
	printf("m_nNetMask:%u\n",m_nNetMask);
   
    break;    
  } // for
  close(sock);
  return true;
}

int main()
{
	bool bool_value = queryLocalIpAddrInfos();
	printf("main:%d\n",bool_value);
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值