Socket.cc revision 40161064
140161064SShuo Chen// Copyright 2010, Shuo Chen.  All rights reserved.
240161064SShuo Chen// http://code.google.com/p/muduo/
340161064SShuo Chen//
440161064SShuo Chen// Use of this source code is governed by a BSD-style license
540161064SShuo Chen// that can be found in the License file.
640161064SShuo Chen
740161064SShuo Chen// Author: Shuo Chen (chenshuo at chenshuo dot com)
840161064SShuo Chen
940161064SShuo Chen#include "Socket.h"
1040161064SShuo Chen
1140161064SShuo Chen#include "InetAddress.h"
1240161064SShuo Chen#include "SocketsOps.h"
1340161064SShuo Chen
1440161064SShuo Chen#include <netinet/in.h>
1540161064SShuo Chen#include <netinet/tcp.h>
1640161064SShuo Chen#include <strings.h>  // bzero
1740161064SShuo Chen
1840161064SShuo Chenusing namespace muduo;
1940161064SShuo Chen
2040161064SShuo ChenSocket::~Socket()
2140161064SShuo Chen{
2240161064SShuo Chen  sockets::close(sockfd_);
2340161064SShuo Chen}
2440161064SShuo Chen
2540161064SShuo Chenvoid Socket::bindAddress(const InetAddress& addr)
2640161064SShuo Chen{
2740161064SShuo Chen  sockets::bindOrDie(sockfd_, addr.getSockAddrInet());
2840161064SShuo Chen}
2940161064SShuo Chen
3040161064SShuo Chenvoid Socket::listen()
3140161064SShuo Chen{
3240161064SShuo Chen  sockets::listenOrDie(sockfd_);
3340161064SShuo Chen}
3440161064SShuo Chen
3540161064SShuo Chenint Socket::accept(InetAddress* peeraddr)
3640161064SShuo Chen{
3740161064SShuo Chen  struct sockaddr_in addr;
3840161064SShuo Chen  bzero(&addr, sizeof addr);
3940161064SShuo Chen  int connfd = sockets::accept(sockfd_, &addr);
4040161064SShuo Chen  if (connfd >= 0)
4140161064SShuo Chen  {
4240161064SShuo Chen    peeraddr->setSockAddrInet(addr);
4340161064SShuo Chen  }
4440161064SShuo Chen  return connfd;
4540161064SShuo Chen}
4640161064SShuo Chen
4740161064SShuo Chenvoid Socket::setReuseAddr(bool on)
4840161064SShuo Chen{
4940161064SShuo Chen  int optval = on ? 1 : 0;
5040161064SShuo Chen  ::setsockopt(sockfd_, SOL_SOCKET, SO_REUSEADDR,
5140161064SShuo Chen               &optval, sizeof optval);
5240161064SShuo Chen  // FIXME CHECK
5340161064SShuo Chen}
5440161064SShuo Chen
5540161064SShuo Chenvoid Socket::shutdownWrite()
5640161064SShuo Chen{
5740161064SShuo Chen  sockets::shutdownWrite(sockfd_);
5840161064SShuo Chen}
5940161064SShuo Chen
6040161064SShuo Chenvoid Socket::setTcpNoDelay(bool on)
6140161064SShuo Chen{
6240161064SShuo Chen  int optval = on ? 1 : 0;
6340161064SShuo Chen  ::setsockopt(sockfd_, IPPROTO_TCP, TCP_NODELAY,
6440161064SShuo Chen               &optval, sizeof optval);
6540161064SShuo Chen  // FIXME CHECK
6640161064SShuo Chen}
6740161064SShuo Chen
68