1 // Copyright 2013 The Chromium Authors
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 #include "build/build_config.h"
8
9 #if BUILDFLAG(IS_WIN)
10 #include <ws2tcpip.h>
11
12 #include "net/base/winsock_init.h"
13 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
14 #include <sys/socket.h>
15 #include <sys/types.h>
16 #endif
17
18 #if BUILDFLAG(IS_APPLE)
19 #include <unistd.h>
20 #endif
21
22 namespace net {
23
CreatePlatformSocket(int family,int type,int protocol)24 SocketDescriptor CreatePlatformSocket(int family, int type, int protocol) {
25 #if BUILDFLAG(IS_WIN)
26 EnsureWinsockInit();
27 SocketDescriptor result = ::WSASocket(family, type, protocol, nullptr, 0,
28 WSA_FLAG_OVERLAPPED);
29 if (result != kInvalidSocket && family == AF_INET6) {
30 DWORD value = 0;
31 if (setsockopt(result, IPPROTO_IPV6, IPV6_V6ONLY,
32 reinterpret_cast<const char*>(&value), sizeof(value))) {
33 closesocket(result);
34 return kInvalidSocket;
35 }
36 }
37 return result;
38 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
39 SocketDescriptor result = ::socket(family, type, protocol);
40 #if BUILDFLAG(IS_APPLE)
41 // Disable SIGPIPE on this socket. Although Chromium globally disables
42 // SIGPIPE, the net stack may be used in other consumers which do not do
43 // this. SO_NOSIGPIPE is a Mac-only API. On Linux, it is a flag on send.
44 if (result != kInvalidSocket) {
45 int value = 1;
46 if (setsockopt(result, SOL_SOCKET, SO_NOSIGPIPE, &value, sizeof(value))) {
47 close(result);
48 return kInvalidSocket;
49 }
50 }
51 #endif
52 return result;
53 #endif // BUILDFLAG(IS_WIN)
54 }
55
56 } // namespace net
57