1efbfdb0cSShuo Chen#pragma once
2efbfdb0cSShuo Chen#include "Common.h"
3efbfdb0cSShuo Chen
4efbfdb0cSShuo Chen#include <utility>  // swap
524ca08a8SShuo Chen#include <netinet/in.h>
6efbfdb0cSShuo Chen
7efbfdb0cSShuo Chenclass InetAddress;
8efbfdb0cSShuo Chen
9efbfdb0cSShuo Chen// RAII handle for socket fd
10efbfdb0cSShuo Chenclass Socket : noncopyable
11efbfdb0cSShuo Chen{
12efbfdb0cSShuo Chen public:
13efbfdb0cSShuo Chen  explicit Socket(int sockfd);
14355c2bf7SShuo Chen  ~Socket();  // close sockfd_
15efbfdb0cSShuo Chen
16efbfdb0cSShuo Chen  Socket(Socket&& rhs)
17efbfdb0cSShuo Chen    : Socket(rhs.sockfd_)
18efbfdb0cSShuo Chen  {
19efbfdb0cSShuo Chen    rhs.sockfd_ = -1;
20efbfdb0cSShuo Chen  }
21efbfdb0cSShuo Chen
22efbfdb0cSShuo Chen  Socket& operator=(Socket&& rhs)
23efbfdb0cSShuo Chen  {
24efbfdb0cSShuo Chen    swap(rhs);
25efbfdb0cSShuo Chen    return *this;
26efbfdb0cSShuo Chen  }
27efbfdb0cSShuo Chen
28efbfdb0cSShuo Chen  void swap(Socket& rhs)
29efbfdb0cSShuo Chen  {
30efbfdb0cSShuo Chen    std::swap(sockfd_, rhs.sockfd_);
31efbfdb0cSShuo Chen  }
32efbfdb0cSShuo Chen
33efbfdb0cSShuo Chen  int fd() { return sockfd_; }
34efbfdb0cSShuo Chen
35efbfdb0cSShuo Chen  // Sockets API
36efbfdb0cSShuo Chen  void bindOrDie(const InetAddress& addr);
37efbfdb0cSShuo Chen  void listenOrDie();
388f04b50cSShuo Chen  // return 0 on success
398f04b50cSShuo Chen  int connect(const InetAddress& addr);
40a52ee0fdSShuo Chen  void shutdownWrite();
418f04b50cSShuo Chen
428f04b50cSShuo Chen  void setReuseAddr(bool on);
43a52ee0fdSShuo Chen  void setTcpNoDelay(bool on);
44efbfdb0cSShuo Chen
45f41285cfSShuo Chen  InetAddress getLocalAddr() const;
46f41285cfSShuo Chen  InetAddress getPeerAddr() const;
47f41285cfSShuo Chen
488bdf4aafSShuo Chen  int recv(void* buf, int len);
498bdf4aafSShuo Chen  int send(const void* buf, int len);
50aafef3ccSShuo Chen
51efbfdb0cSShuo Chen  // factory methods
5224ca08a8SShuo Chen  static Socket createTCP(sa_family_t family);  // AF_INET or AF_INET6
5324ca08a8SShuo Chen  static Socket createUDP(sa_family_t family);  // AF_INET or AF_INET6
54efbfdb0cSShuo Chen
55efbfdb0cSShuo Chen private:
56efbfdb0cSShuo Chen  int sockfd_;
57efbfdb0cSShuo Chen};
58