From b16f9a6176bfac30c0e7d29ec6df37e750fd1c60 Mon Sep 17 00:00:00 2001 From: aozhiwei Date: Mon, 21 Jun 2021 05:27:52 +0000 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0GetLocalIp?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- a8/sysutils.cc | 24 ++++++++++++++++++++++++ a8/sysutils.h | 1 + 2 files changed, 25 insertions(+) diff --git a/a8/sysutils.cc b/a8/sysutils.cc index c3cd3d8..e266e8a 100644 --- a/a8/sysutils.cc +++ b/a8/sysutils.cc @@ -5,6 +5,9 @@ #include #include +#include +#include + #include #include @@ -167,6 +170,27 @@ namespace a8 return std::string(buf); } + bool GetLocalIp(std::string& ip_address) + { + int sfd, intr; + struct ifreq buf[16]; + struct ifconf ifc; + sfd = ::socket(AF_INET, SOCK_DGRAM, 0); + if (sfd < 0) { + return false; + } + ifc.ifc_len = sizeof(buf); + ifc.ifc_buf = (caddr_t)buf; + if (::ioctl(sfd, SIOCGIFCONF, (char *)&ifc)) { + return false; + } + intr = ifc.ifc_len / sizeof(struct ifreq); + while (intr-- > 0 && ::ioctl(sfd, SIOCGIFADDR, (char *)&buf[intr])); + ::close(sfd); + ip_address = inet_ntoa(((struct sockaddr_in*)(&buf[intr].ifr_addr))-> sin_addr); + return true; + } + std::string FormatDateTime(time_t time_val) { struct tm tm_time = {0}; diff --git a/a8/sysutils.h b/a8/sysutils.h index 140bfd1..9710661 100644 --- a/a8/sysutils.h +++ b/a8/sysutils.h @@ -76,6 +76,7 @@ namespace a8 bool MkDir(const std::string& path); void ForceCreateDir(const std::string& path); std::string GetIpAddress(unsigned long ip_saddr); + bool GetLocalIp(std::string& ip_address); std::string FormatDateTime(time_t time_val); std::string TimestampToDateTime(time_t time_val);