[runtime] Fix DISABLE_REFLECTION_EMIT build.
[mono.git] / mono / utils / networking-fallback.c
1 /**
2  * \file
3  * Fallback networking code that rely on old BSD apis or whatever else is available.
4  *
5  * Author:
6  *      Rodrigo Kumpera (kumpera@gmail.com)
7  *
8  * (C) 2015 Xamarin
9  */
10
11 #include <mono/utils/networking.h>
12 #include <glib.h>
13
14 #ifdef HAVE_NETDB_H
15 #include <netdb.h>
16 #endif
17
18 #if !defined (HAVE_GETADDRINFO) 
19
20 #if defined (HAVE_GETHOSTBYNAME) || defined (HAVE_GETHOSTBYNAME2)
21
22 static void
23 add_hostent (MonoAddressInfo *info, int flags, struct hostent *h)
24 {
25         MonoAddressEntry *cur, *prev = info->entries;
26         int idx = 0;
27
28         if (!h)
29                 return;
30
31         if (!info->aliases)
32                 info->aliases = g_strdupv (h->h_aliases);
33
34         while (h->h_addr_list [idx]) {
35                 cur = g_new0 (MonoAddressEntry, 1);
36                 if (prev)
37                         prev->next = cur;
38                 else
39                         info->entries = cur;
40
41                 if (flags & MONO_HINT_CANONICAL_NAME && h->h_name)
42                         cur->canonical_name = g_strdup (h->h_name);
43
44                 cur->family = h->h_addrtype;
45                 cur->socktype = SOCK_STREAM;
46                 cur->protocol = 0; /* Zero means the default stream protocol */
47                 cur->address_len = h->h_length;
48                 memcpy (&cur->address, h->h_addr_list [idx], h->h_length);
49
50                 prev = cur;
51                 ++idx;
52         }
53 }
54
55 int
56 mono_get_address_info (const char *hostname, int port, int flags, MonoAddressInfo **result)
57 {
58         MonoAddressInfo *addr_info;
59         addr_info = g_new0 (MonoAddressInfo, 1);
60
61 #ifdef HAVE_GETHOSTBYNAME2
62         if (flags & MONO_HINT_IPV6 || flags & MONO_HINT_UNSPECIFIED)
63                 add_hostent (addr_info, flags, gethostbyname2 (hostname, AF_INET6));
64         if (flags & MONO_HINT_IPV4 || flags & MONO_HINT_UNSPECIFIED)
65                 add_hostent (addr_info, flags, gethostbyname2 (hostname, AF_INET));
66 #else
67         add_hostent (addr_info, flags, gethostbyname (hostname))
68 #endif
69
70         if (!addr_info->entries) {
71                 *result = NULL;
72                 mono_free_address_info (addr_info);
73                 return 1;               
74         }
75
76         *result = addr_info;
77         return 0;
78 }
79
80 #endif /* defined (HAVE_GETHOSTBYNAME) || defined (HAVE_GETHOSTBYNAME2) */
81
82 #endif /* !defined (HAVE_GETADDRINFO) */