⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ifaddrs.c

📁 glibc 库, 不仅可以学习使用库函数,还可以学习函数的具体实现,是提高功力的好资料
💻 C
📖 第 1 页 / 共 2 页
字号:
/* getifaddrs -- get names and addresses of all network interfaces   Copyright (C) 2003, 2004, 2005, 2006, 2007 Free Software Foundation, Inc.   This file is part of the GNU C Library.   The GNU C Library is free software; you can redistribute it and/or   modify it under the terms of the GNU Lesser General Public   License as published by the Free Software Foundation; either   version 2.1 of the License, or (at your option) any later version.   The GNU C Library is distributed in the hope that it will be useful,   but WITHOUT ANY WARRANTY; without even the implied warranty of   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU   Lesser General Public License for more details.   You should have received a copy of the GNU Lesser General Public   License along with the GNU C Library; if not, write to the Free   Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA   02111-1307 USA.  */#include <alloca.h>#include <assert.h>#include <errno.h>#include <ifaddrs.h>#include <net/if.h>#include <netinet/in.h>#include <netpacket/packet.h>#include <stdbool.h>#include <stdint.h>#include <stdlib.h>#include <string.h>#include <sys/ioctl.h>#include <sys/socket.h>#include <sysdep.h>#include <time.h>#include <unistd.h>#include "netlinkaccess.h"/* We don't know if we have NETLINK support compiled in in our   Kernel, so include the old implementation as fallback.  */#if __ASSUME_NETLINK_SUPPORT == 0int __no_netlink_support attribute_hidden;# define getifaddrs fallback_getifaddrs# include "sysdeps/gnu/ifaddrs.c"# undef getifaddrs#endif/* struct to hold the data for one ifaddrs entry, so we can allocate   everything at once.  */struct ifaddrs_storage{  struct ifaddrs ifa;  union  {    /* Save space for the biggest of the four used sockaddr types and       avoid a lot of casts.  */    struct sockaddr sa;    struct sockaddr_ll sl;    struct sockaddr_in s4;    struct sockaddr_in6 s6;  } addr, netmask, broadaddr;  char name[IF_NAMESIZE + 1];};void__netlink_free_handle (struct netlink_handle *h){  struct netlink_res *ptr;  int saved_errno = errno;  ptr = h->nlm_list;  while (ptr != NULL)    {      struct netlink_res *tmpptr;      tmpptr = ptr->next;      free (ptr);      ptr = tmpptr;    }  __set_errno (saved_errno);}static int__netlink_sendreq (struct netlink_handle *h, int type){  struct req  {    struct nlmsghdr nlh;    struct rtgenmsg g;    char pad[0];  } req;  struct sockaddr_nl nladdr;  if (h->seq == 0)    h->seq = time (NULL);  req.nlh.nlmsg_len = sizeof (req);  req.nlh.nlmsg_type = type;  req.nlh.nlmsg_flags = NLM_F_ROOT | NLM_F_MATCH | NLM_F_REQUEST;  req.nlh.nlmsg_pid = 0;  req.nlh.nlmsg_seq = h->seq;  req.g.rtgen_family = AF_UNSPEC;  if (sizeof (req) != offsetof (struct req, pad))    memset (req.pad, '\0', sizeof (req) - offsetof (struct req, pad));  memset (&nladdr, '\0', sizeof (nladdr));  nladdr.nl_family = AF_NETLINK;  return TEMP_FAILURE_RETRY (__sendto (h->fd, (void *) &req, sizeof (req), 0,				       (struct sockaddr *) &nladdr,				       sizeof (nladdr)));}int__netlink_request (struct netlink_handle *h, int type){  struct netlink_res *nlm_next;  struct sockaddr_nl nladdr;  struct nlmsghdr *nlmh;  ssize_t read_len;  bool done = false;#ifdef PAGE_SIZE  /* Help the compiler optimize out the malloc call if PAGE_SIZE     is constant and smaller or equal to PTHREAD_STACK_MIN/4.  */  const size_t buf_size = PAGE_SIZE;#else  const size_t buf_size = __getpagesize ();#endif  bool use_malloc = false;  char *buf;  if (__libc_use_alloca (buf_size))    buf = alloca (buf_size);  else    {      buf = malloc (buf_size);      if (buf != NULL)	use_malloc = true;      else	goto out_fail;    }  struct iovec iov = { buf, buf_size };  if (__netlink_sendreq (h, type) < 0)    goto out_fail;  while (! done)    {      struct msghdr msg =	{	  (void *) &nladdr, sizeof (nladdr),	  &iov, 1,	  NULL, 0,	  0	};      read_len = TEMP_FAILURE_RETRY (__recvmsg (h->fd, &msg, 0));      if (read_len < 0)	goto out_fail;      if (nladdr.nl_pid != 0)	continue;      if (__builtin_expect (msg.msg_flags & MSG_TRUNC, 0))	goto out_fail;      size_t count = 0;      size_t remaining_len = read_len;      for (nlmh = (struct nlmsghdr *) buf;	   NLMSG_OK (nlmh, remaining_len);	   nlmh = (struct nlmsghdr *) NLMSG_NEXT (nlmh, remaining_len))	{	  if ((pid_t) nlmh->nlmsg_pid != h->pid	      || nlmh->nlmsg_seq != h->seq)	    continue;	  ++count;	  if (nlmh->nlmsg_type == NLMSG_DONE)	    {	      /* We found the end, leave the loop.  */	      done = true;	      break;	    }	  if (nlmh->nlmsg_type == NLMSG_ERROR)	    {	      struct nlmsgerr *nlerr = (struct nlmsgerr *) NLMSG_DATA (nlmh);	      if (nlmh->nlmsg_len < NLMSG_LENGTH (sizeof (struct nlmsgerr)))		errno = EIO;	      else		errno = -nlerr->error;	      goto out_fail;	    }	}      /* If there was nothing with the expected nlmsg_pid and nlmsg_seq,	 there is no point to record it.  */      if (count == 0)	continue;      nlm_next = (struct netlink_res *) malloc (sizeof (struct netlink_res)						+ read_len);      if (nlm_next == NULL)	goto out_fail;      nlm_next->next = NULL;      nlm_next->nlh = memcpy (nlm_next + 1, buf, read_len);      nlm_next->size = read_len;      nlm_next->seq = h->seq;      if (h->nlm_list == NULL)	h->nlm_list = nlm_next;      else	h->end_ptr->next = nlm_next;      h->end_ptr = nlm_next;    }  if (use_malloc)    free (buf);  return 0;out_fail:  if (use_malloc)    free (buf);  return -1;}void__netlink_close (struct netlink_handle *h){  /* Don't modify errno.  */  INTERNAL_SYSCALL_DECL (err);  (void) INTERNAL_SYSCALL (close, err, 1, h->fd);}/* Open a NETLINK socket.  */int__netlink_open (struct netlink_handle *h){  struct sockaddr_nl nladdr;  h->fd = __socket (PF_NETLINK, SOCK_RAW, NETLINK_ROUTE);  if (h->fd < 0)    goto out;  memset (&nladdr, '\0', sizeof (nladdr));  nladdr.nl_family = AF_NETLINK;  if (__bind (h->fd, (struct sockaddr *) &nladdr, sizeof (nladdr)) < 0)    {    close_and_out:      __netlink_close (h);    out:#if __ASSUME_NETLINK_SUPPORT == 0      __no_netlink_support = 1;#endif      return -1;    }  /* Determine the ID the kernel assigned for this netlink connection.     It is not necessarily the PID if there is more than one socket     open.  */  socklen_t addr_len = sizeof (nladdr);  if (__getsockname (h->fd, (struct sockaddr *) &nladdr, &addr_len) < 0)    goto close_and_out;  h->pid = nladdr.nl_pid;  return 0;}/* We know the number of RTM_NEWLINK entries, so we reserve the first   # of entries for this type. All RTM_NEWADDR entries have an index   pointer to the RTM_NEWLINK entry.  To find the entry, create   a table to map kernel index entries to our index numbers.   Since we get at first all RTM_NEWLINK entries, it can never happen   that a RTM_NEWADDR index is not known to this map.  */static intinternal_functionmap_newlink (int index, struct ifaddrs_storage *ifas, int *map, int max){  int i;  for (i = 0; i < max; i++)    {      if (map[i] == -1)	{	  map[i] = index;	  if (i > 0)	    ifas[i - 1].ifa.ifa_next = &ifas[i].ifa;	  return i;	}      else if (map[i] == index)	return i;    }  /* This should never be reached. If this will be reached, we have     a very big problem.  */  abort ();}/* Create a linked list of `struct ifaddrs' structures, one for each   network interface on the host machine.  If successful, store the   list in *IFAP and return 0.  On errors, return -1 and set `errno'.  */intgetifaddrs (struct ifaddrs **ifap){  struct netlink_handle nh = { 0, 0, 0, NULL, NULL };  struct netlink_res *nlp;  struct ifaddrs_storage *ifas;  unsigned int i, newlink, newaddr, newaddr_idx;  int *map_newlink_data;  size_t ifa_data_size = 0;  /* Size to allocate for all ifa_data.  */  char *ifa_data_ptr;	/* Pointer to the unused part of memory for				ifa_data.  */  int result = 0;  *ifap = NULL;  if (! __no_netlink_support && __netlink_open (&nh) < 0)    {#if __ASSUME_NETLINK_SUPPORT != 0      return -1;#endif    }#if __ASSUME_NETLINK_SUPPORT == 0  if (__no_netlink_support)    return fallback_getifaddrs (ifap);#endif  /* Tell the kernel that we wish to get a list of all     active interfaces, collect all data for every interface.  */  if (__netlink_request (&nh, RTM_GETLINK) < 0)    {      result = -1;      goto exit_free;    }  /* Now ask the kernel for all addresses which are assigned     to an interface and collect all data for every interface.     Since we store the addresses after the interfaces in the     list, we will later always find the interface before the     corresponding addresses.  */  ++nh.seq;  if (__netlink_request (&nh, RTM_GETADDR) < 0)    {      result = -1;      goto exit_free;    }  /* Count all RTM_NEWLINK and RTM_NEWADDR entries to allocate     enough memory.  */  newlink = newaddr = 0;  for (nlp = nh.nlm_list; nlp; nlp = nlp->next)    {      struct nlmsghdr *nlh;      size_t size = nlp->size;      if (nlp->nlh == NULL)	continue;      /* Walk through all entries we got from the kernel and look, which	 message type they contain.  */      for (nlh = nlp->nlh; NLMSG_OK (nlh, size); nlh = NLMSG_NEXT (nlh, size))	{	  /* Check if the message is what we want.  */	  if ((pid_t) nlh->nlmsg_pid != nh.pid || nlh->nlmsg_seq != nlp->seq)	    continue;	  if (nlh->nlmsg_type == NLMSG_DONE)	    break;		/* ok */	  if (nlh->nlmsg_type == RTM_NEWLINK)	    {	      /* A RTM_NEWLINK message can have IFLA_STATS data. We need to		 know the size before creating the list to allocate enough		 memory.  */	      struct ifinfomsg *ifim = (struct ifinfomsg *) NLMSG_DATA (nlh);	      struct rtattr *rta = IFLA_RTA (ifim);	      size_t rtasize = IFLA_PAYLOAD (nlh);	      while (RTA_OK (rta, rtasize))		{		  size_t rta_payload = RTA_PAYLOAD (rta);		  if (rta->rta_type == IFLA_STATS)		    {		      ifa_data_size += rta_payload;		      break;		    }		  else		    rta = RTA_NEXT (rta, rtasize);		}	      ++newlink;	    }	  else if (nlh->nlmsg_type == RTM_NEWADDR)	    ++newaddr;	}    }  /* Return if no interface is up.  */  if ((newlink + newaddr) == 0)    goto exit_free;  /* Allocate memory for all entries we have and initialize next     pointer.  */

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -