socket_descriptor.cc 1.6 KB

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