2 * Copyright 2016 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>
22 #include <gtest/gtest.h>
26 TEST(AsyncSocketTest, getSockOpt) {
28 std::shared_ptr<AsyncSocket> socket =
29 AsyncSocket::newSocket(&evb, 0);
34 int expectedRc = getsockopt(socket->getFd(), SOL_SOCKET,
35 SO_REUSEADDR, &val, &len);
36 int actualRc = socket->getSockOpt(SOL_SOCKET, SO_REUSEADDR, &val, &len);
38 EXPECT_EQ(expectedRc, actualRc);
41 TEST(AsyncSocketTest, REUSEPORT) {
43 auto serverSocket = AsyncServerSocket::newSocket(&base);
44 serverSocket->bind(0);
45 serverSocket->listen(0);
46 serverSocket->startAccepting();
49 serverSocket->setReusePortEnabled(true);
51 LOG(INFO) << "Reuse port probably not supported";
55 SocketAddress address;
56 serverSocket->getAddress(&address);
57 int port = address.getPort();
59 auto serverSocket2 = AsyncServerSocket::newSocket(&base);
60 serverSocket2->setReusePortEnabled(true);
61 serverSocket2->bind(port);
62 serverSocket2->listen(0);
63 serverSocket2->startAccepting();
67 TEST(AsyncSocketTest, v4v6samePort) {
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());
79 TEST(AsyncSocketTest, duplicateBind) {
81 auto server1 = AsyncServerSocket::newSocket(&base);
85 SocketAddress address;
86 server1->getAddress(std::addressof(address));
88 auto server2 = AsyncServerSocket::newSocket(&base);
89 EXPECT_THROW(server2->bind(address.getPort()), std::exception);