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