1// Copyright 2013 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "nacl_io/ossocket.h"
6#if defined(PROVIDES_SOCKET_API) && !defined(__GLIBC__)
7
8#include <errno.h>
9#include <string.h>
10
11#include <iostream>
12#include <sstream>
13#include <string>
14
15#include "sdk_util/macros.h"
16
17
18EXTERN_C_BEGIN
19
20const char* inet_ntop(int af, const void* src, char* dst, socklen_t size) {
21  if (AF_INET == af) {
22    if (size < INET_ADDRSTRLEN) {
23      errno = ENOSPC;
24      return NULL;
25    }
26    struct in_addr in;
27    memcpy(&in, src, sizeof(in));
28    char* result = inet_ntoa(in);
29    memcpy(dst, result, strlen(result) + 1);
30    return dst;
31  }
32
33  if (AF_INET6 == af) {
34    if (size < INET6_ADDRSTRLEN) {
35      errno = ENOSPC;
36      return NULL;
37    }
38    const uint8_t* tuples = static_cast<const uint8_t*>(src);
39    std::stringstream output;
40    for (int i = 0; i < 8; i++) {
41      uint16_t tuple = (tuples[2*i] << 8) + tuples[2*i+1];
42      output << std::hex << tuple;
43      if (i < 7) {
44        output << ":";
45      }
46    }
47    memcpy(dst, output.str().c_str(), output.str().size() + 1);
48    return dst;
49  }
50
51  errno = EAFNOSUPPORT;
52  return NULL;
53}
54
55EXTERN_C_END
56
57#endif  // defined(PROVIDES_SOCKET_API) && !defined(__GLIBC__)
58
59