1e254a845SShuo Chen// Copyright 2010, Shuo Chen.  All rights reserved.
2e254a845SShuo Chen// http://code.google.com/p/muduo/
3e254a845SShuo Chen//
4e254a845SShuo Chen// Use of this source code is governed by a BSD-style license
5e254a845SShuo Chen// that can be found in the License file.
6e254a845SShuo Chen
7e254a845SShuo Chen// Author: Shuo Chen (chenshuo at chenshuo dot com)
8e254a845SShuo Chen
9e254a845SShuo Chen#include "Socket.h"
10e254a845SShuo Chen
11e254a845SShuo Chen#include "InetAddress.h"
12e254a845SShuo Chen#include "SocketsOps.h"
13e254a845SShuo Chen
14e254a845SShuo Chen#include <netinet/in.h>
15e254a845SShuo Chen#include <netinet/tcp.h>
16e254a845SShuo Chen#include <strings.h>  // bzero
17e254a845SShuo Chen
18e254a845SShuo Chenusing namespace muduo;
19e254a845SShuo Chen
20e254a845SShuo ChenSocket::~Socket()
21e254a845SShuo Chen{
22e254a845SShuo Chen  sockets::close(sockfd_);
23e254a845SShuo Chen}
24e254a845SShuo Chen
25e254a845SShuo Chenvoid Socket::bindAddress(const InetAddress& addr)
26e254a845SShuo Chen{
27e254a845SShuo Chen  sockets::bindOrDie(sockfd_, addr.getSockAddrInet());
28e254a845SShuo Chen}
29e254a845SShuo Chen
30e254a845SShuo Chenvoid Socket::listen()
31e254a845SShuo Chen{
32e254a845SShuo Chen  sockets::listenOrDie(sockfd_);
33e254a845SShuo Chen}
34e254a845SShuo Chen
35e254a845SShuo Chenint Socket::accept(InetAddress* peeraddr)
36e254a845SShuo Chen{
37e254a845SShuo Chen  struct sockaddr_in addr;
38e254a845SShuo Chen  bzero(&addr, sizeof addr);
39e254a845SShuo Chen  int connfd = sockets::accept(sockfd_, &addr);
40e254a845SShuo Chen  if (connfd >= 0)
41e254a845SShuo Chen  {
42e254a845SShuo Chen    peeraddr->setSockAddrInet(addr);
43e254a845SShuo Chen  }
44e254a845SShuo Chen  return connfd;
45e254a845SShuo Chen}
46e254a845SShuo Chen
47e254a845SShuo Chenvoid Socket::setReuseAddr(bool on)
48e254a845SShuo Chen{
49e254a845SShuo Chen  int optval = on ? 1 : 0;
50e254a845SShuo Chen  ::setsockopt(sockfd_, SOL_SOCKET, SO_REUSEADDR,
51e254a845SShuo Chen               &optval, sizeof optval);
52e254a845SShuo Chen  // FIXME CHECK
53e254a845SShuo Chen}
54e254a845SShuo Chen
55e254a845SShuo Chenvoid Socket::shutdownWrite()
56e254a845SShuo Chen{
57e254a845SShuo Chen  sockets::shutdownWrite(sockfd_);
58e254a845SShuo Chen}
59e254a845SShuo Chen
60e254a845SShuo Chenvoid Socket::setTcpNoDelay(bool on)
61e254a845SShuo Chen{
62e254a845SShuo Chen  int optval = on ? 1 : 0;
63e254a845SShuo Chen  ::setsockopt(sockfd_, IPPROTO_TCP, TCP_NODELAY,
64e254a845SShuo Chen               &optval, sizeof optval);
65e254a845SShuo Chen  // FIXME CHECK
66e254a845SShuo Chen}
67e254a845SShuo Chen
68