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