xref: /PHP-5.3/win32/inet.c (revision e61c2e8c)
1 #include "config.w32.h"
2 #if (_WIN32_WINNT < 0x0600) /* Vista/2k8 have these functions */
3 #include "php.h"
4 #include <winsock2.h>
5 #include <windows.h>
6 #include <Ws2tcpip.h>
7 
8 #include "inet.h"
9 
inet_pton(int af,const char * src,void * dst)10 PHPAPI int inet_pton(int af, const char* src, void* dst)
11 {
12 	int address_length;
13 	struct sockaddr_storage sa;
14 	struct sockaddr_in *sin = (struct sockaddr_in *)&sa;
15 	struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&sa;
16 
17 	switch (af) {
18 		case AF_INET:
19 			address_length = sizeof (struct sockaddr_in);
20 			break;
21 
22 		case AF_INET6:
23 			address_length = sizeof (struct sockaddr_in6);
24 			break;
25 
26 		default:
27 			return -1;
28 	}
29 
30 	if (WSAStringToAddress ((LPTSTR) src, af, NULL, (LPSOCKADDR) &sa, &address_length) == 0) {
31 		switch (af) {
32 			case AF_INET:
33 				memcpy (dst, &sin->sin_addr, sizeof (struct in_addr));
34 				break;
35 
36 			case AF_INET6:
37 				memcpy (dst, &sin6->sin6_addr, sizeof (struct in6_addr));
38 				break;
39 		}
40 		return 1;
41 	}
42 
43 	return 0;
44 }
45 
inet_ntop(int af,const void * src,char * dst,size_t size)46 PHPAPI const char* inet_ntop(int af, const void* src, char* dst, size_t size)
47 {
48 	int address_length;
49 	DWORD string_length = size;
50 	struct sockaddr_storage sa;
51 	struct sockaddr_in *sin = (struct sockaddr_in *)&sa;
52 	struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&sa;
53 
54 	memset (&sa, 0, sizeof (sa));
55 	switch (af) {
56 		case AF_INET:
57 			address_length = sizeof (struct sockaddr_in);
58 			sin->sin_family = af;
59 			memcpy (&sin->sin_addr, src, sizeof (struct in_addr));
60 			break;
61 
62 		case AF_INET6:
63 			address_length = sizeof (struct sockaddr_in6);
64 			sin6->sin6_family = af;
65 			memcpy (&sin6->sin6_addr, src, sizeof (struct in6_addr));
66 			break;
67 
68 		default:
69 			return NULL;
70 	}
71 
72 	if (WSAAddressToString ((LPSOCKADDR) &sa, address_length, NULL, dst, &string_length) == 0) {
73 		return dst;
74 	}
75 
76 	return NULL;
77 }
78 
inet_aton(const char * cp,struct in_addr * inp)79 int inet_aton(const char *cp, struct in_addr *inp) {
80   inp->s_addr = inet_addr(cp);
81 
82   if (inp->s_addr == INADDR_NONE) {
83           return 0;
84   }
85 
86   return 1;
87 }
88 #endif
89