你这样实现不能获取到准确使用的ip地址,能否通过socket获取到当前使用的本地ip
时间: 2024-03-20 13:38:48 浏览: 15
是的,可以通过 socket 获取当前使用的本地 IP 地址。下面给出具体实现:
```c++
#include <iostream>
#include <string>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
int main() {
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(80);
addr.sin_addr.s_addr = inet_addr("8.8.8.8");
connect(sockfd, (sockaddr*) &addr, sizeof(addr));
sockaddr_in localAddr;
socklen_t localAddrLen = sizeof(localAddr);
getsockname(sockfd, (sockaddr*) &localAddr, &localAddrLen);
char addressBuffer[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &localAddr.sin_addr, addressBuffer, INET_ADDRSTRLEN);
std::string localIpAddress = addressBuffer;
std::cout << "Local IP Address: " << localIpAddress << std::endl;
close(sockfd);
return 0;
}
```
在上述代码中,我们创建了一个 UDP 套接字,并通过 `connect()` 函数连接到了一个公网 IP 地址。然后,我们调用 `getsockname()` 函数获取到了该套接字的本地 IP 地址,最后通过 `inet_ntop()` 函数将 IP 地址转换成字符串格式。