Home | History | Annotate | Download | only in socket
      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 "net/socket/socket_descriptor.h"
      6 
      7 #if defined(OS_POSIX)
      8 #include <sys/types.h>
      9 #include <sys/socket.h>
     10 #endif
     11 
     12 #include "base/basictypes.h"
     13 
     14 #if defined(OS_WIN)
     15 #include <ws2tcpip.h>
     16 #include "base/win/windows_version.h"
     17 #include "net/base/winsock_init.h"
     18 #endif
     19 
     20 namespace net {
     21 
     22 PlatformSocketFactory* g_socket_factory = NULL;
     23 
     24 PlatformSocketFactory::PlatformSocketFactory() {
     25 }
     26 
     27 PlatformSocketFactory::~PlatformSocketFactory() {
     28 }
     29 
     30 void PlatformSocketFactory::SetInstance(PlatformSocketFactory* factory) {
     31   g_socket_factory = factory;
     32 }
     33 
     34 SocketDescriptor CreateSocketDefault(int family, int type, int protocol) {
     35 #if defined(OS_WIN)
     36   EnsureWinsockInit();
     37   SocketDescriptor result = ::WSASocket(family, type, protocol, NULL, 0,
     38                                         WSA_FLAG_OVERLAPPED);
     39   if (result != kInvalidSocket && family == AF_INET6 &&
     40       base::win::OSInfo::GetInstance()->version() >= base::win::VERSION_VISTA) {
     41     DWORD value = 0;
     42     if (setsockopt(result, IPPROTO_IPV6, IPV6_V6ONLY,
     43                    reinterpret_cast<const char*>(&value), sizeof(value))) {
     44       closesocket(result);
     45       return kInvalidSocket;
     46     }
     47   }
     48   return result;
     49 #else  // OS_WIN
     50   return ::socket(family, type, protocol);
     51 #endif  // OS_WIN
     52 }
     53 
     54 SocketDescriptor CreatePlatformSocket(int family, int type, int protocol) {
     55   if (g_socket_factory)
     56     return g_socket_factory->CreateSocket(family, type, protocol);
     57   else
     58     return CreateSocketDefault(family, type, protocol);
     59 }
     60 
     61 }  // namespace net
     62