How do I output my host’s IP addresses from a C program?

后端 未结 8 659
猫巷女王i
猫巷女王i 2020-12-03 21:19

I need to display all the IP addresses from my local computer, using the C language. How can this be done?

8条回答
  •  长情又很酷
    2020-12-03 22:07

    Another way to do it in C. I do have to say though.... there are so many ways to do it from the shell, what's the point?

    #include 
    #include 
    #include 
    #include 
    
    #include 
    #include 
    #include 
    #include 
    #include 
    
    
    void show_address_info( struct ifaddrs *ifa ){
      struct sockaddr_in *s4;
      struct sockaddr_in6 *s6;
      /* ipv6 addresses have to fit in this buffer */
      char buf[64];
    
      if (AF_INET == ifa->ifa_addr->sa_family){
        s4 = (struct sockaddr_in *)(ifa->ifa_addr);
        if (NULL == inet_ntop(ifa->ifa_addr->sa_family, (void *)&(s4->sin_addr), buf, sizeof(buf))){
          printf("%s: inet_ntop failed!\n", ifa->ifa_name);
        } else {
          printf("IPv4 addr %s: %s\n", ifa->ifa_name, buf);
        }
      }
      else if (AF_INET6 == ifa->ifa_addr->sa_family) {
        s6 = (struct sockaddr_in6 *)(ifa->ifa_addr);
        if (NULL == inet_ntop(ifa->ifa_addr->sa_family, (void *)&(s6->sin6_addr), buf, sizeof(buf))) {
          printf("%s: inet_ntop failed!\n", ifa->ifa_name);
        } else {
          printf("IPv6 addr %s: %s\n", ifa->ifa_name, buf);
          }
      }
    
    }
    
    
    int main(int argc, char **argv){
      struct ifaddrs *myaddrs, *ifa;
      int status;
    
      status = getifaddrs(&myaddrs);
      if (status != 0){
        perror("getifaddrs failed!");
        exit(1);
      }
    
      for (ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next){
        if (NULL == ifa->ifa_addr){
          continue;
        }
        if ((ifa->ifa_flags & IFF_UP) == 0) {
          continue;
        }
        show_address_info(ifa);
      }
      freeifaddrs(myaddrs);
      return 0;
    }
    

提交回复
热议问题