用C++写一个获取本地IP
时间: 2023-02-26 15:04:31 浏览: 140
在 C 语言中,可以使用 socket 函数库获取本地 IP 地址。
以下是一个简单的代码示例:
```
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
int main() {
int status;
struct addrinfo hints;
struct addrinfo *servinfo; // will point to the results
char ipstr[INET6_ADDRSTRLEN];
memset(&hints, 0, sizeof hints); // make sure the struct is empty
hints.ai_family = AF_UNSPEC; // don't care IPv4 or IPv6
hints.ai_socktype = SOCK_STREAM; // TCP stream sockets
if ((status = getaddrinfo("www.google.com", NULL, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
return 1;
}
struct addrinfo *p;
for (p = servinfo; p != NULL; p = p->ai_next) {
void *addr;
char *ipver;
// get the pointer to the address itself,
// different fields in IPv4 and IPv6:
if (p->ai_family == AF_INET) { // IPv4
struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;
addr = &(ipv4->sin_addr);
ipver = "IPv4";
} else { // IPv6
struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;
addr = &(ipv6->sin6_addr);
ipver = "IPv6";
}
// convert the IP to a string and print it:
inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr);
printf("%s: %s\n", ipver, ipstr);
}
freeaddrinfo(servinfo); // free the linked-list
return 0;
}
```
该代码通过获取 `www.google.com` 的 IP 地址来展示如何使用 `getaddrinfo` 函数。如果要获取本地 IP 地址,请将主机名替换为 `localhost` 或 `127.0.0.1`。
阅读全文