|
| 1 | +#include "pal_networking.h" |
| 2 | + |
| 3 | +#include <arpa/inet.h> |
| 4 | +#include <pthread.h> |
| 5 | +#include <semaphore.h> |
| 6 | +#include <stdio.h> |
| 7 | +#include <stdlib.h> |
| 8 | +#include <sys/socket.h> |
| 9 | +#include <string.h> |
| 10 | + |
| 11 | +struct state |
| 12 | +{ |
| 13 | + HostEntry entry; |
| 14 | + char* hostName; |
| 15 | + int errorCode; |
| 16 | + sem_t semaphore; |
| 17 | +}; |
| 18 | + |
| 19 | +static void callback(HostEntry* entry, int errorCode) |
| 20 | +{ |
| 21 | + printf("(%lu) handler: enter, errorCode: %d\n", pthread_self(), errorCode); |
| 22 | + |
| 23 | + struct state* state = (struct state*)entry; |
| 24 | + |
| 25 | + if (errorCode == 0) |
| 26 | + { |
| 27 | + printf("(%lu) callback: # of addresses = %d\n", pthread_self(), entry->IPAddressCount); |
| 28 | + for (int i = 0; i < entry->IPAddressCount; ++i) |
| 29 | + { |
| 30 | + IPAddress ipAddress = entry->IPAddressList[i]; |
| 31 | + |
| 32 | + char buffer[256]; |
| 33 | + inet_ntop(ipAddress.IsIPv6 ? AF_INET6 : AF_INET, ipAddress.Address, buffer, sizeof(buffer)); |
| 34 | + printf("(%lu) ip for %s: %s\n", pthread_self(), entry->CanonicalName, buffer); |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + state->errorCode = errorCode; |
| 39 | + |
| 40 | + sem_post(&state->semaphore); |
| 41 | +} |
| 42 | + |
| 43 | +int main(int argc, char** argv) |
| 44 | +{ |
| 45 | + if (argc != 2) |
| 46 | + { |
| 47 | + printf("hostname must be given as argument\n"); |
| 48 | + return EXIT_FAILURE; |
| 49 | + } |
| 50 | + |
| 51 | + if (!SystemNative_PlatformSupportsGetAddrInfoAsync()) |
| 52 | + { |
| 53 | + printf("platform support not available\n"); |
| 54 | + return EXIT_FAILURE; |
| 55 | + } |
| 56 | + |
| 57 | + printf("platform support available\n"); |
| 58 | + |
| 59 | + char* hostName = argv[1]; |
| 60 | + printf("(%lu) hostname: %s\n", pthread_self(), hostName); |
| 61 | + |
| 62 | + if (strcmp(hostName, "null")==0) |
| 63 | + { |
| 64 | + hostName = NULL; |
| 65 | + } |
| 66 | + |
| 67 | + struct state state; |
| 68 | + sem_init(&state.semaphore, 0, 0); |
| 69 | + |
| 70 | + int error = SystemNative_GetHostEntryForNameAsync((uint8_t*)hostName, &state.entry, callback); |
| 71 | + |
| 72 | + if (error != 0) |
| 73 | + { |
| 74 | + printf("(%lu) OS call failed with error %d\n", pthread_self(), error); |
| 75 | + return EXIT_FAILURE; |
| 76 | + } |
| 77 | + |
| 78 | + printf("(%lu) main: waiting for semaphore\n", pthread_self()); |
| 79 | + |
| 80 | + sem_wait(&state.semaphore); |
| 81 | + sem_destroy(&state.semaphore); |
| 82 | + |
| 83 | + printf("(%lu) main: exit, errorCode: %d\n", pthread_self(), state.errorCode); |
| 84 | + |
| 85 | + return state.errorCode; |
| 86 | +} |
0 commit comments