[IOMultiplexerV2] alpha
[NextIRCd.git] / src / IOHandler / compat / inet.c
1 /* inet.c - IOMultiplexer
2  * Copyright (C) 2014  Philipp Kreil (pk910)
3  * 
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  * 
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  * 
14  * You should have received a copy of the GNU General Public License 
15  * along with this program. If not, see <http://www.gnu.org/licenses/>. 
16  */
17 #include "../IOHandler_config.h"
18
19 #include <stdlib.h>
20 #include <string.h>
21 #include <stdio.h>
22
23 #ifdef WIN32
24 #include <winsock2.h>
25 #include <ws2tcpip.h>
26 #else
27 /* non-win32 systems have these functions defined... */
28 #endif
29
30 #ifndef HAVE_INET_PTON
31 #ifdef WIN32
32 int inet_pton(int af, const char *src, void *dst) {
33         struct sockaddr_storage ss;
34         int size = sizeof(ss);
35         char src_copy[INET6_ADDRSTRLEN+1];
36
37         memset(&ss, 0, sizeof(ss));
38         /* stupid non-const API */
39         strncpy (src_copy, src, INET6_ADDRSTRLEN+1);
40         src_copy[INET6_ADDRSTRLEN] = 0;
41
42         if(WSAStringToAddress(src_copy, af, NULL, (struct sockaddr *)&ss, &size) == 0) {
43                 switch(af) {
44                 case AF_INET:
45                         *(struct in_addr *)dst = ((struct sockaddr_in *)&ss)->sin_addr;
46                         return 1;
47                 case AF_INET6:
48                         *(struct in6_addr *)dst = ((struct sockaddr_in6 *)&ss)->sin6_addr;
49                         return 1;
50                 }
51         }
52         return 0;
53 }
54 #else
55
56
57 #endif
58 #endif
59
60 #ifndef HAVE_INET_NTOP
61 #ifdef WIN32
62 const char *inet_ntop(int af, const void *src, char *dst, socklen_t size) {
63         struct sockaddr_storage ss;
64         unsigned long s = size;
65
66         memset(&ss, 0, sizeof(ss));
67         ss.ss_family = af;
68
69         switch(af) {
70         case AF_INET:
71                 ((struct sockaddr_in *)&ss)->sin_addr = *(struct in_addr *)src;
72                 break;
73         case AF_INET6:
74                 ((struct sockaddr_in6 *)&ss)->sin6_addr = *(struct in6_addr *)src;
75                 break;
76         default:
77                 return NULL;
78         }
79         /* cannot direclty use &size because of strict aliasing rules */
80         return (WSAAddressToString((struct sockaddr *)&ss, sizeof(ss), NULL, dst, &s) == 0) ? dst : NULL;
81 }
82 #else
83
84
85 #endif
86 #endif