利用ifaddrs结构体中的if_data计算即时网速

首先我拜读了这篇博客中的做法,但是当我调试好文中的程序后,显示的网速却一直是0.

http://blog.csdn.net/ieczw/article/details/41011603   

文中利用了ifaddrs中最后一个元素if_data,但是这个结构体到底是什么结构,找不到他的文档。所以只有试着输出,看看里面的内容。

/* The `getifaddrs' function generates a linked list of these structures.
   Each element of the list describes one network interface.  */
struct ifaddrs
{
  struct ifaddrs *ifa_next; /* Pointer to the next structure.  */

  char *ifa_name;       /* Name of this network interface.  */
  unsigned int ifa_flags;   /* Flags as from SIOCGIFFLAGS ioctl.  */

  struct sockaddr *ifa_addr;    /* Network address of this interface.  */
  struct sockaddr *ifa_netmask; /* Netmask of this interface.  */
  union
  {
    /* At most one of the following two is valid.  If the IFF_BROADCAST
       bit is set in `ifa_flags', then `ifa_broadaddr' is valid.  If the
       IFF_POINTOPOINT bit is set, then `ifa_dstaddr' is valid.
       It is never the case that both these bits are set at once.  */
    struct sockaddr *ifu_broadaddr; /* Broadcast address of this interface. */
    struct sockaddr *ifu_dstaddr; /* Point-to-point destination address.  */
  } ifa_ifu;
  /* These very same macros are defined by <net/if.h> for `struct ifaddr'.
     So if they are defined already, the existing definitions will be fine.  */
# ifndef ifa_broadaddr
#  define ifa_broadaddr ifa_ifu.ifu_broadaddr
# endif
# ifndef ifa_dstaddr
#  define ifa_dstaddr   ifa_ifu.ifu_dstaddr
# endif 
        
  void *ifa_data;       /* Address-specific data (may be unused).  */
};

所以我在程序上添加了很多占位元素将if_data中的内容尽可能多的输出

有点蛮力的做法,但是能看到内容就行。运行后数结果如下面右图所示:

除了前两个u_long和第十一个有数据,其他的均为0

在对比一下ifconfig的内容和if_data中的内容,会发现第一个u_long就是RX packages,第二个就是RX bytes,根据这个可以计算出下载的网速。之前出错是因为使用了第3,4个ulong来计算但是其一直是0.

所以暂且利用第二个值计算了一下接收数据的速度。修改过程遇到个问题:

直接将u_long强制类型转换为float的出入很大,将其先转化为int类型参与运算,运算过程中和float类型的数据运算,最后得到float类型的数据。

  int rawspeed=ndev.ifs_ispeed;
  printf("--------------%d ",rawspeed);
  ispeed = rawspeed * 1.0/(ndev.ifs_us/1000 * 0.001);
  printf("%s: Rec Speed: %f MB/s || Down Speed: %f MB/s ",
  ndev.ifs_name,ispeed/(1024.0*1024.0),ospeed/(1024.0*1024.0));

最终结果:

左侧是程序算出的接收速度,右侧是用nload测出速度,由于计量单位不同,将bit值除以8,之后看以看出,测出的速度还是比较准确的。

原文地址:https://www.cnblogs.com/littleby/p/7251281.html