gpt4 book ai didi

c - 使用 UDP 套接字通过 connect()ing 获取我自己的 IP 地址?

转载 作者:太空宇宙 更新时间:2023-11-04 08:36:50 27 4
gpt4 key购买 nike

我听说我可以获得自己的 IP 地址(不是 127.0.0.1),方法是创建一个 UDP socket 并将 connecting() 连接到像 Google 这样的有效目标 IP 地址。

但是,我找不到任何引用或示例。

这可能吗?如果可以,我该怎么做?


char* get_my_ip() {
int sockfd;
struct sockaddr_storage remoteaddr; // client address
socklen_t addrlen;
char remoteIP[INET6_ADDRSTRLEN];
char *ip_addr;
ip_addr = malloc(sizeof(char) * INET6_ADDRSTRLEN);
int rv;

struct addrinfo hints, *ai, *p;

memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_DGRAM;
if ((rv = getaddrinfo("8.8.8.8", "http", &hints, &ai)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
exit(1);
}
// loop through all the results and make a socket
for(p = ai; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror("UDP: socket");
continue;
}

if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
perror("UDP: connect");
continue;
}
break;
}
if (p == NULL) {
fprintf(stderr, "UDP: failed to bind socket\n");
exit(2);
}

getsockname(sockfd, (struct sockaddr*)&remoteaddr, &addrlen);

// deal with both IPv4 and IPv6:
if (remoteaddr.ss_family == AF_INET) {
struct sockaddr_in *s = (struct sockaddr_in *)&remoteaddr;
inet_ntop(AF_INET, &s->sin_addr, remoteIP, addrlen);
}
else { // AF_INET6
struct sockaddr_in6 *s = (struct sockaddr_in6 *)&remoteaddr;
inet_ntop(AF_INET6, &s->sin6_addr, remoteIP, addrlen);
}
printf("IP_ADDRESS:%s", remoteIP);

freeaddrinfo(ai); // all done with this structure
close(sockfd);

strcpy(ip_addr, remoteIP);
return ip_addr;
}

最佳答案

调用 connect() 然后在你的套接字上调用 getsockname()。它将返回套接字现在绑定(bind)到的 IP 地址,IP 路由表已将其选为到目标地址的最佳路由。

但这不一定是您要查找的 IP 地址,除非您只有一个外部 IP 地址。

如果您在调制解调器或路由器的另一端谈论您的公共(public) IP 地址,则此技术根本不适用。

关于c - 使用 UDP 套接字通过 connect()ing 获取我自己的 IP 地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25879280/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com