Created
May 9, 2020 11:44
-
-
Save bfreuden/ee6fd78de42dd4fc92357cbf0f0e895b to your computer and use it in GitHub Desktop.
Wait until getaddrinfo returns an IP address
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <string.h> | |
| #include <stdlib.h> | |
| #include <netdb.h> | |
| #include <sys/types.h> | |
| #include <sys/socket.h> | |
| #include <arpa/inet.h> | |
| #include <time.h> | |
| #include <errno.h> | |
| int msleep(long msec) | |
| { | |
| struct timespec ts; | |
| int res; | |
| if (msec < 0) | |
| { | |
| errno = EINVAL; | |
| return -1; | |
| } | |
| ts.tv_sec = msec / 1000; | |
| ts.tv_nsec = (msec % 1000) *1000000; | |
| do { | |
| res = nanosleep(&ts, &ts); | |
| } while (res && errno == EINTR); | |
| return res; | |
| } | |
| int main(int argc, char *argv[]) | |
| { | |
| int error, max_wait_ms, sleep_ms; | |
| struct addrinfo hints, *res; | |
| int errcode; | |
| char addrstr[100]; | |
| void *ptr; | |
| memset(&hints, 0, sizeof(hints)); | |
| hints.ai_family = PF_UNSPEC; | |
| hints.ai_socktype = SOCK_STREAM; | |
| hints.ai_flags |= AI_CANONNAME; | |
| if (argc != 2) | |
| { | |
| fprintf(stderr, "missing command line parameter: %s\n", "test<hostname>"); | |
| return 1; | |
| } | |
| max_wait_ms = 60000; | |
| sleep_ms = 500; | |
| while (max_wait_ms > 0) | |
| { | |
| /*resolve the domain name into a list of addresses */ | |
| error = getaddrinfo(argv[1], NULL, NULL, &res); | |
| if (error != 0) | |
| { | |
| if (error == EAI_SYSTEM) | |
| { | |
| perror("getaddrinfo"); | |
| } | |
| else | |
| { | |
| fprintf(stderr, "error in getaddrinfo: %s\n", gai_strerror(error)); | |
| } | |
| /*exit(EXIT_FAILURE); */ | |
| /*return 0; */ | |
| max_wait_ms -= sleep_ms; | |
| msleep(sleep_ms); | |
| } | |
| else | |
| { | |
| while (res) | |
| { | |
| inet_ntop(res->ai_family, res->ai_addr->sa_data, addrstr, 100); | |
| switch (res->ai_family) | |
| { | |
| case AF_INET: | |
| ptr = &((struct sockaddr_in *) res->ai_addr)->sin_addr; | |
| break; | |
| case AF_INET6: | |
| ptr = &((struct sockaddr_in6 *) res->ai_addr)->sin6_addr; | |
| break; | |
| } | |
| inet_ntop(res->ai_family, ptr, addrstr, 100); | |
| printf("IPv%d address: %s (%s)\n", res->ai_family == PF_INET6 ? 6 : 4, | |
| addrstr, res->ai_canonname); | |
| res = res->ai_next; | |
| } | |
| break; | |
| } | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment