原先使用检举网卡的方式获取ip地址,例如:
ACE示例:
ACE_INET_Addr *the_addr_array;
size_t count = 0;
string ip;
int rc = ACE::get_ip_interfaces (count , the_addr_array);
char address[30];
int i = 0;
while (i < count)
{
(the_addr_array+i)->addr_to_string(address, sizeof(address));
if (strcmp("172",address)||strcmp("192",address))
{
//ip = address;
ip = StrSplit(address,":")[0];
}
printf("%s\n", address);
i++;
}
delete [] the_addr_array;
当遇到使用docker或更多虚拟网卡时,导致ip获取困难,有时候不知道具体用的是哪个网卡。
所以使用了socket编程中的getsockname函数来获取本机的IP地址。它创建了一个UDP socket,并连接到一个公共的DNS服务器地址(这里使用了Google的DNS服务器地址8.8.8.8),然后通过getsockname函数获取本机的IP地址。
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;
int main (int args,char**argv){
char buffer[1024];
struct sockaddr_in sa;
socklen_t len;
int sockfd = socket(AF_INET, SOCK_DGRAM, 0); //UDP
if (sockfd < 0) {
perror("socket");
exit(1);
}
memset(&sa, 0, sizeof(struct sockaddr_in));
sa.sin_family = AF_INET;
sa.sin_addr.s_addr = inet_addr("8.8.8.8"); // 使用一个公共的DNS服务器地址
sa.sin_port = htons(53);
if (connect(sockfd, (struct sockaddr *)&sa, sizeof(struct sockaddr_in)) < 0) {
perror("connect");
exit(1);
}
len = sizeof(sa);
if (getsockname(sockfd, (struct sockaddr *)&sa, &len) < 0) {
perror("getsockname");
exit(1);
}
printf("本机IP地址: %s\n", inet_ntop(AF_INET, &(sa.sin_addr), buffer, sizeof(buffer)));
close(sockfd);
return 0;
}
本机IP地址: 172.20.108.16
以上暂时解决获取ip 问题,如果还遇到坑再更新。欢迎指正,或者分享其他场景