using C code to get same info as ifconfig

前端 未结 6 816
醉话见心
醉话见心 2020-11-27 03:15

Is there a way in Linux, using C code, to get the same information that \"ifconfig eth0\" would return? I\'m interested in things like IP address, link status, and MAC addr

6条回答
  •  情话喂你
    2020-11-27 04:07

    One way to get to the bottom of problems like this, particularly in cases when you don't have source, is strace.

    It gives you a list of all the system calls made by any program you pass it, along with their arguments and return values. If your program just dumps some info and quits rather than running for an extended time it can be pretty straightforward to just do a man on all the system calls you see that look like they might provide the info you're looking for.

    When I run

    strace ifconfig
    

    Some of the interesting calls are:

    open("/proc/net/dev", O_RDONLY)         = 6
    

    followed by a bunch of ioctls, corroborating @payne's answer:

    ioctl(5, SIOCGIFFLAGS, {ifr_name="eth0",    ifr_flags=IFF_UP|IFF_BROADCAST|IFF_RUNNING|IFF_MULTICAST}) = 0
    ioctl(5, SIOCGIFHWADDR, {ifr_name="eth0", ifr_hwaddr=84:2b:2b:b7:9e:6d}) = 0
    ioctl(5, SIOCGIFMETRIC, {ifr_name="eth0", ifr_metric=0}) = 0
    ioctl(5, SIOCGIFMTU, {ifr_name="eth0", ifr_mtu=1500}) = 0
    

提交回复
热议问题