要从UDP套接字(C/C++)获取本地IP地址,可以使用以下步骤:
#include<iostream>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#include<stdio.h>
#include <stdlib.h>
void getLocalIPAddress() {
// 初始化WSA
WSADATA wsaData;
int result = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (result != 0) {
std::cout << "WSAStartup failed: "<< result<< std::endl;
return;
}
// 创建UDP套接字
SOCKET sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sock == INVALID_SOCKET) {
std::cout << "socket failed: " << WSAGetLastError()<< std::endl;
WSACleanup();
return;
}
// 设置套接字选项
struct sockaddr_in sa;
sa.sin_family = AF_INET;
sa.sin_addr.s_addr = htonl(INADDR_ANY);
sa.sin_port = htons(0);
if (bind(sock, (SOCKADDR*)&sa, sizeof(sa)) == SOCKET_ERROR) {
std::cout << "bind failed: " << WSAGetLastError()<< std::endl;
closesocket(sock);
WSACleanup();
return;
}
// 获取本地IP地址
INTERFACE_INFO InterfaceList[20];
unsigned long nBytesReturned;
if (WSAIoctl(sock, SIO_GET_INTERFACE_LIST, NULL, 0, &InterfaceList, sizeof(InterfaceList), &nBytesReturned, NULL, NULL) == SOCKET_ERROR) {
std::cout << "WSAIoctl failed: " << WSAGetLastError()<< std::endl;
closesocket(sock);
WSACleanup();
return;
}
int count = nBytesReturned / sizeof(INTERFACE_INFO);
for (int i = 0; i< count; ++i) {
sockaddr_in *pAddress = (sockaddr_in*)&(InterfaceList[i].iiAddress);
char ipAddress[20];
inet_ntop(AF_INET, &(pAddress->sin_addr), ipAddress, sizeof(ipAddress));
std::cout << "IP Address: " << ipAddress<< std::endl;
}
// 关闭套接字并清理WSA
closesocket(sock);
WSACleanup();
}
getLocalIPAddress()
函数。int main() {
getLocalIPAddress();
return 0;
}
这样,你就可以从UDP套接字获取本地IP地址了。请注意,这个示例仅适用于Windows操作系统,并依赖于Winsock2库。如果你使用的是其他操作系统或库,请根据相应的文档进行修改。
领取专属 10元无门槛券
手把手带您无忧上云