2 * Copyright 2017 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 #include <folly/io/async/AsyncSocket.h>
19 #include <folly/io/async/AsyncServerSocket.h>
20 #include <folly/io/async/EventBase.h>
21 #include <folly/portability/GTest.h>
25 TEST(AsyncSocketTest, getSockOpt) {
27 std::shared_ptr<AsyncSocket> socket =
28 AsyncSocket::newSocket(&evb, 0);
33 int expectedRc = getsockopt(socket->getFd(), SOL_SOCKET,
34 SO_REUSEADDR, &val, &len);
35 int actualRc = socket->getSockOpt(SOL_SOCKET, SO_REUSEADDR, &val, &len);
37 EXPECT_EQ(expectedRc, actualRc);
40 TEST(AsyncSocketTest, REUSEPORT) {
42 auto serverSocket = AsyncServerSocket::newSocket(&base);
43 serverSocket->bind(0);
44 serverSocket->listen(0);
45 serverSocket->startAccepting();
48 serverSocket->setReusePortEnabled(true);
50 LOG(INFO) << "Reuse port probably not supported";
54 SocketAddress address;
55 serverSocket->getAddress(&address);
56 int port = address.getPort();
58 auto serverSocket2 = AsyncServerSocket::newSocket(&base);
59 serverSocket2->setReusePortEnabled(true);
60 serverSocket2->bind(port);
61 serverSocket2->listen(0);
62 serverSocket2->startAccepting();
66 TEST(AsyncSocketTest, v4v6samePort) {
68 auto serverSocket = AsyncServerSocket::newSocket(&base);
69 serverSocket->bind(0);
70 auto addrs = serverSocket->getAddresses();
71 ASSERT_GT(addrs.size(), 0);
72 uint16_t port = addrs[0].getPort();
73 for (const auto& addr : addrs) {
74 EXPECT_EQ(port, addr.getPort());
78 TEST(AsyncSocketTest, duplicateBind) {
80 auto server1 = AsyncServerSocket::newSocket(&base);
84 SocketAddress address;
85 server1->getAddress(std::addressof(address));
87 auto server2 = AsyncServerSocket::newSocket(&base);
88 EXPECT_THROW(server2->bind(address.getPort()), std::exception);