summaryrefslogtreecommitdiff
path: root/win32/inet.c
blob: b794bcaeb45d23fdeae2bf711567942a3c24c784 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include "config.w32.h"
#if (_WIN32_WINNT < 0x0600) /* Vista/2k8 have these functions */
#include "php.h"
#include <winsock2.h>
#include <windows.h>
#include <Ws2tcpip.h>

#include "inet.h"

PHPAPI int inet_pton(int af, const char* src, void* dst)
{
	int address_length;
	struct sockaddr_storage sa;
	struct sockaddr_in *sin = (struct sockaddr_in *)&sa;
	struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&sa;

	switch (af) {
		case AF_INET:
			address_length = sizeof (struct sockaddr_in);
			break;

		case AF_INET6:
			address_length = sizeof (struct sockaddr_in6);
			break;

		default:
			return -1;
	}

	if (WSAStringToAddress ((LPTSTR) src, af, NULL, (LPSOCKADDR) &sa, &address_length) == 0) {
		switch (af) {
			case AF_INET:
				memcpy (dst, &sin->sin_addr, sizeof (struct in_addr));
				break;

			case AF_INET6:
				memcpy (dst, &sin6->sin6_addr, sizeof (struct in6_addr));
				break;
		}
		return 1;
	}

	return 0;
}

PHPAPI const char* inet_ntop(int af, const void* src, char* dst, size_t size)
{
	int address_length;
	DWORD string_length = size;
	struct sockaddr_storage sa;
	struct sockaddr_in *sin = (struct sockaddr_in *)&sa;
	struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&sa;

	memset (&sa, 0, sizeof (sa));
	switch (af) {
		case AF_INET:
			address_length = sizeof (struct sockaddr_in);
			sin->sin_family = af;
			memcpy (&sin->sin_addr, src, sizeof (struct in_addr));
			break;

		case AF_INET6:
			address_length = sizeof (struct sockaddr_in6);
			sin6->sin6_family = af;
			memcpy (&sin6->sin6_addr, src, sizeof (struct in6_addr));
			break;

		default:
			return NULL;
	}

	if (WSAAddressToString ((LPSOCKADDR) &sa, address_length, NULL, dst, &string_length) == 0) {
		return dst;
	}

	return NULL;
}

int inet_aton(const char *cp, struct in_addr *inp) {
  inp->s_addr = inet_addr(cp);

  if (inp->s_addr == INADDR_NONE) {
          return 0;
  }

  return 1;
}
#endif