fix flaky ConnectTFOTimeout and ConnectTFOFallbackTimeout tests
[folly.git] / folly / io / async / test / AsyncSocketTest.cpp
1 /*
2  * Copyright 2016 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #include <iostream>
17
18 #include <folly/io/async/AsyncSocket.h>
19 #include <folly/io/async/AsyncServerSocket.h>
20 #include <folly/io/async/EventBase.h>
21
22 #include <gtest/gtest.h>
23
24 namespace folly {
25
26 TEST(AsyncSocketTest, getSockOpt) {
27   EventBase evb;
28   std::shared_ptr<AsyncSocket> socket =
29     AsyncSocket::newSocket(&evb, 0);
30
31   int val;
32   socklen_t len;
33
34   int expectedRc = getsockopt(socket->getFd(), SOL_SOCKET,
35                               SO_REUSEADDR, &val, &len);
36   int actualRc = socket->getSockOpt(SOL_SOCKET, SO_REUSEADDR, &val, &len);
37
38   EXPECT_EQ(expectedRc, actualRc);
39 }
40
41 TEST(AsyncSocketTest, REUSEPORT) {
42   EventBase base;
43   auto serverSocket = AsyncServerSocket::newSocket(&base);
44   serverSocket->bind(0);
45   serverSocket->listen(0);
46   serverSocket->startAccepting();
47
48   try {
49     serverSocket->setReusePortEnabled(true);
50   } catch(...) {
51     LOG(INFO) << "Reuse port probably not supported";
52     return;
53   }
54
55   SocketAddress address;
56   serverSocket->getAddress(&address);
57   int port = address.getPort();
58
59   auto serverSocket2 = AsyncServerSocket::newSocket(&base);
60   serverSocket2->setReusePortEnabled(true);
61   serverSocket2->bind(port);
62   serverSocket2->listen(0);
63   serverSocket2->startAccepting();
64
65 }
66
67 TEST(AsyncSocketTest, v4v6samePort) {
68   EventBase base;
69   auto serverSocket = AsyncServerSocket::newSocket(&base);
70   serverSocket->bind(0);
71   auto addrs = serverSocket->getAddresses();
72   ASSERT_GT(addrs.size(), 0);
73   uint16_t port = addrs[0].getPort();
74   for (const auto& addr : addrs) {
75     EXPECT_EQ(port, addr.getPort());
76   }
77 }
78
79 TEST(AsyncSocketTest, duplicateBind) {
80   EventBase base;
81   auto server1 = AsyncServerSocket::newSocket(&base);
82   server1->bind(0);
83   server1->listen(10);
84
85   SocketAddress address;
86   server1->getAddress(std::addressof(address));
87
88   auto server2 = AsyncServerSocket::newSocket(&base);
89   EXPECT_THROW(server2->bind(address.getPort()), std::exception);
90 }
91
92 } // namespace