Merge pull request #1464 from akoeplinger/fix-portable-target
[mono.git] / mono / utils / networking.c
1 /*
2  * networking.c: Portable networking functions
3  *
4  * Author:
5  *      Rodrigo Kumpera (kumpera@gmail.com)
6  *
7  * (C) 2015 Xamarin
8  */
9
10 #include <mono/utils/networking.h>
11 #include <glib.h>
12
13 int
14 mono_address_size_for_family (int family)
15 {
16         switch (family) {
17         case AF_INET:
18                 return sizeof (struct in_addr);
19         case AF_INET6:
20                 return sizeof (struct in6_addr);
21         }
22         return 0;
23 }
24
25
26 void
27 mono_free_address_info (MonoAddressInfo *ai)
28 {
29         MonoAddressEntry *cur = ai->entries, *next;
30         while (cur) {
31                 next = cur->next;
32                 g_free ((void*)cur->canonical_name);
33                 g_free (cur);
34                 cur = next;
35         }
36         g_strfreev (ai->aliases);
37         g_free (ai);
38 }
39
40
41 /* port in host order, address in network order */
42 void
43 mono_socket_address_init (MonoSocketAddress *sa, socklen_t *len, int family, const void *address, int port)
44 {
45         memset (sa, 0, sizeof (MonoSocketAddress));
46         if (family == AF_INET) {
47                 *len = sizeof (struct sockaddr_in);
48
49                 sa->v4.sin_family = family;
50                 sa->v4.sin_addr = *(struct in_addr*)address;
51                 sa->v4.sin_port = htons (port);
52 #if HAVE_SOCKADDR_IN_SIN_LEN
53                 sa->v4.sin_len = sizeof (*len);
54 #endif
55         } else if (family == AF_INET6) {
56                 *len = sizeof (struct sockaddr_in6);
57
58                 sa->v6.sin6_family = family;
59                 sa->v6.sin6_addr = *(struct in6_addr*)address;
60                 sa->v6.sin6_port = htons (port);
61 #if HAVE_SOCKADDR_IN6_SIN_LEN
62                 sa->v6.sin6_len = sizeof (*len);
63 #endif
64         } else {
65                 g_error ("Cannot handle address family %d", family);
66         }
67 }
68
69 void
70 mono_address_init (MonoAddress *out_addr, int family, void *in_addr)
71 {
72         memset (out_addr, 0, sizeof (MonoAddress));
73         out_addr->family = family;
74         memcpy (&out_addr->addr, in_addr, mono_address_size_for_family (family));
75 }