添加GetLocalIp

This commit is contained in:
aozhiwei 2021-06-21 05:27:52 +00:00
parent f0ee3fb68f
commit b16f9a6176
2 changed files with 25 additions and 0 deletions

View File

@ -5,6 +5,9 @@
#include <arpa/inet.h>
#include <memory.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <a8/a8.h>
#include <a8/sysutils.h>
@ -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};

View File

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