19a1e991dSShuo Chen// Copyright 2010, Shuo Chen.  All rights reserved.
29a1e991dSShuo Chen// http://code.google.com/p/muduo/
39a1e991dSShuo Chen//
49a1e991dSShuo Chen// Use of this source code is governed by a BSD-style license
59a1e991dSShuo Chen// that can be found in the License file.
69a1e991dSShuo Chen
79a1e991dSShuo Chen// Author: Shuo Chen (chenshuo at chenshuo dot com)
89a1e991dSShuo Chen
99a1e991dSShuo Chen#include "Socket.h"
109a1e991dSShuo Chen
119a1e991dSShuo Chen#include "InetAddress.h"
129a1e991dSShuo Chen#include "SocketsOps.h"
139a1e991dSShuo Chen
149a1e991dSShuo Chen#include <netinet/in.h>
159a1e991dSShuo Chen#include <netinet/tcp.h>
169a1e991dSShuo Chen#include <strings.h>  // bzero
179a1e991dSShuo Chen
189a1e991dSShuo Chenusing namespace muduo;
199a1e991dSShuo Chen
209a1e991dSShuo ChenSocket::~Socket()
219a1e991dSShuo Chen{
229a1e991dSShuo Chen  sockets::close(sockfd_);
239a1e991dSShuo Chen}
249a1e991dSShuo Chen
259a1e991dSShuo Chenvoid Socket::bindAddress(const InetAddress& addr)
269a1e991dSShuo Chen{
279a1e991dSShuo Chen  sockets::bindOrDie(sockfd_, addr.getSockAddrInet());
289a1e991dSShuo Chen}
299a1e991dSShuo Chen
309a1e991dSShuo Chenvoid Socket::listen()
319a1e991dSShuo Chen{
329a1e991dSShuo Chen  sockets::listenOrDie(sockfd_);
339a1e991dSShuo Chen}
349a1e991dSShuo Chen
359a1e991dSShuo Chenint Socket::accept(InetAddress* peeraddr)
369a1e991dSShuo Chen{
379a1e991dSShuo Chen  struct sockaddr_in addr;
389a1e991dSShuo Chen  bzero(&addr, sizeof addr);
399a1e991dSShuo Chen  int connfd = sockets::accept(sockfd_, &addr);
409a1e991dSShuo Chen  if (connfd >= 0)
419a1e991dSShuo Chen  {
429a1e991dSShuo Chen    peeraddr->setSockAddrInet(addr);
439a1e991dSShuo Chen  }
449a1e991dSShuo Chen  return connfd;
459a1e991dSShuo Chen}
469a1e991dSShuo Chen
479a1e991dSShuo Chenvoid Socket::setReuseAddr(bool on)
489a1e991dSShuo Chen{
499a1e991dSShuo Chen  int optval = on ? 1 : 0;
509a1e991dSShuo Chen  ::setsockopt(sockfd_, SOL_SOCKET, SO_REUSEADDR,
519a1e991dSShuo Chen               &optval, sizeof optval);
529a1e991dSShuo Chen  // FIXME CHECK
539a1e991dSShuo Chen}
549a1e991dSShuo Chen
55