Socket.cc revision 65c497a3
165c497a3SShuo Chen// Copyright 2010, Shuo Chen.  All rights reserved.
265c497a3SShuo Chen// http://code.google.com/p/muduo/
365c497a3SShuo Chen//
465c497a3SShuo Chen// Use of this source code is governed by a BSD-style license
565c497a3SShuo Chen// that can be found in the License file.
665c497a3SShuo Chen
765c497a3SShuo Chen// Author: Shuo Chen (chenshuo at chenshuo dot com)
865c497a3SShuo Chen
965c497a3SShuo Chen#include "Socket.h"
1065c497a3SShuo Chen
1165c497a3SShuo Chen#include "InetAddress.h"
1265c497a3SShuo Chen#include "SocketsOps.h"
1365c497a3SShuo Chen
1465c497a3SShuo Chen#include <netinet/in.h>
1565c497a3SShuo Chen#include <netinet/tcp.h>
1665c497a3SShuo Chen#include <strings.h>  // bzero
1765c497a3SShuo Chen
1865c497a3SShuo Chenusing namespace muduo;
1965c497a3SShuo Chen
2065c497a3SShuo ChenSocket::~Socket()
2165c497a3SShuo Chen{
2265c497a3SShuo Chen  sockets::close(sockfd_);
2365c497a3SShuo Chen}
2465c497a3SShuo Chen
2565c497a3SShuo Chenvoid Socket::bindAddress(const InetAddress& addr)
2665c497a3SShuo Chen{
2765c497a3SShuo Chen  sockets::bindOrDie(sockfd_, addr.getSockAddrInet());
2865c497a3SShuo Chen}
2965c497a3SShuo Chen
3065c497a3SShuo Chenvoid Socket::listen()
3165c497a3SShuo Chen{
3265c497a3SShuo Chen  sockets::listenOrDie(sockfd_);
3365c497a3SShuo Chen}
3465c497a3SShuo Chen
3565c497a3SShuo Chenint Socket::accept(InetAddress* peeraddr)
3665c497a3SShuo Chen{
3765c497a3SShuo Chen  struct sockaddr_in addr;
3865c497a3SShuo Chen  bzero(&addr, sizeof addr);
3965c497a3SShuo Chen  int connfd = sockets::accept(sockfd_, &addr);
4065c497a3SShuo Chen  if (connfd >= 0)
4165c497a3SShuo Chen  {
4265c497a3SShuo Chen    peeraddr->setSockAddrInet(addr);
4365c497a3SShuo Chen  }
4465c497a3SShuo Chen  return connfd;
4565c497a3SShuo Chen}
4665c497a3SShuo Chen
4765c497a3SShuo Chenvoid Socket::setReuseAddr(bool on)
4865c497a3SShuo Chen{
4965c497a3SShuo Chen  int optval = on ? 1 : 0;
5065c497a3SShuo Chen  ::setsockopt(sockfd_, SOL_SOCKET, SO_REUSEADDR,
5165c497a3SShuo Chen               &optval, sizeof optval);
5265c497a3SShuo Chen  // FIXME CHECK
5365c497a3SShuo Chen}
5465c497a3SShuo Chen
55