cyssmile
#include <iostream>
#include <string>
#include <ifaddrs.h>
#include <arpa/inet.h>
#include <netdb.h>
std::string GetIp() {
  void *tmpAddrPtr = NULL;
  struct ifaddrs *ifAddrStruct = NULL;
  getifaddrs(&ifAddrStruct);

  std::string valid_ip;
  while (ifAddrStruct != NULL) {
    if (ifAddrStruct->ifa_addr->sa_family == AF_INET) {
      tmpAddrPtr = &(reinterpret_cast<struct sockaddr_in *>(ifAddrStruct->ifa_addr))->sin_addr;
      char addressBuffer[INET_ADDRSTRLEN];
      inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
      // std::cout << "Check out ip4: " << ifAddrStruct->ifa_name << ":" << addressBuffer << std::endl;
      std::string str = addressBuffer;
      if (str.substr(0, 1) != "0" && str.substr(0, 3) != "127" && str.substr(0, 3) != "172") {
        valid_ip = str;
        break;
      }
    }
    valid_ip = "get invalid ip ...";
    ifAddrStruct = ifAddrStruct->ifa_next;
  }
  //std::cout << "valid_ip: " << valid_ip << std::endl;
  return valid_ip;
}

int main(){
    std::cout << GetIp() << std::endl;
}

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-05
  • 2021-12-12
  • 2022-12-23
猜你喜欢
  • 2021-06-15
  • 2022-12-23
  • 2021-10-28
  • 2021-09-02
  • 2022-12-23
  • 2021-05-21
相关资源
相似解决方案