1354280cfSShuo Chen// Copyright 2010, Shuo Chen.  All rights reserved.
2354280cfSShuo Chen// http://code.google.com/p/muduo/
3354280cfSShuo Chen//
4354280cfSShuo Chen// Use of this source code is governed by a BSD-style license
5354280cfSShuo Chen// that can be found in the License file.
6354280cfSShuo Chen
7354280cfSShuo Chen// Author: Shuo Chen (chenshuo at chenshuo dot com)
8354280cfSShuo Chen
9354280cfSShuo Chen#include "Socket.h"
10354280cfSShuo Chen
11354280cfSShuo Chen#include "InetAddress.h"
12354280cfSShuo Chen#include "SocketsOps.h"
13354280cfSShuo Chen
14354280cfSShuo Chen#include <netinet/in.h>
15354280cfSShuo Chen#include <netinet/tcp.h>
16354280cfSShuo Chen#include <strings.h>  // bzero
17354280cfSShuo Chen
18354280cfSShuo Chenusing namespace muduo;
19354280cfSShuo Chen
20354280cfSShuo ChenSocket::~Socket()
21354280cfSShuo Chen{
22354280cfSShuo Chen  sockets::close(sockfd_);
23354280cfSShuo Chen}
24354280cfSShuo Chen
25354280cfSShuo Chenvoid Socket::bindAddress(const InetAddress& addr)
26354280cfSShuo Chen{
27354280cfSShuo Chen  sockets::bindOrDie(sockfd_, addr.getSockAddrInet());
28354280cfSShuo Chen}
29354280cfSShuo Chen
30354280cfSShuo Chenvoid Socket::listen()
31354280cfSShuo Chen{
32354280cfSShuo Chen  sockets::listenOrDie(sockfd_);
33354280cfSShuo Chen}
34354280cfSShuo Chen
35354280cfSShuo Chenint Socket::accept(InetAddress* peeraddr)
36354280cfSShuo Chen{
37354280cfSShuo Chen  struct sockaddr_in addr;
38354280cfSShuo Chen  bzero(&addr, sizeof addr);
39354280cfSShuo Chen  int connfd = sockets::accept(sockfd_, &addr);
40354280cfSShuo Chen  if (connfd >= 0)
41354280cfSShuo Chen  {
42354280cfSShuo Chen    peeraddr->setSockAddrInet(addr);
43354280cfSShuo Chen  }
44354280cfSShuo Chen  return connfd;
45354280cfSShuo Chen}
46354280cfSShuo Chen
47354280cfSShuo Chenvoid Socket::setReuseAddr(bool on)
48354280cfSShuo Chen{
49354280cfSShuo Chen  int optval = on ? 1 : 0;
50354280cfSShuo Chen  ::setsockopt(sockfd_, SOL_SOCKET, SO_REUSEADDR,
51354280cfSShuo Chen               &optval, sizeof optval);
52354280cfSShuo Chen  // FIXME CHECK
53354280cfSShuo Chen}
54354280cfSShuo Chen
55354280cfSShuo Chenvoid Socket::shutdownWrite()
56354280cfSShuo Chen{
57354280cfSShuo Chen  sockets::shutdownWrite(sockfd_);
58354280cfSShuo Chen}
59354280cfSShuo Chen
60354280cfSShuo Chenvoid Socket::setTcpNoDelay(bool on)
61354280cfSShuo Chen{
62354280cfSShuo Chen  int optval = on ? 1 : 0;
63354280cfSShuo Chen  ::setsockopt(sockfd_, IPPROTO_TCP, TCP_NODELAY,
64354280cfSShuo Chen               &optval, sizeof optval);
65354280cfSShuo Chen  // FIXME CHECK
66354280cfSShuo Chen}
67354280cfSShuo Chen
68