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);