Meine eigene IP-Adresse durch Verbinden () mit dem UDP-Socket erhalten?
Ich habe gehört, dass ich meine eigene IP-Adresse (nicht 127.0.0.1) erhalten kann, indem ich ein @ erstellUDP socket
und Verbinden () mit einer gültigen Ziel-IP-Adresse wie Google.
Ich konnte jedoch keine Referenz oder Beispiel dafür finden.
Ist das möglich? Wenn ja, wie kann ich das machen?
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;
}