linux socket bind函数,linux下socket编程bind函数返回异常码98 Address already in use(2)

int status = ::send ( m_sock, s.c_str(), s.size(), MSG_NOSIGNAL );

if ( status == -1 )

{

return false;

}

else

{

return true;

}

}

int Socket::recv ( string& s ) const

{

char buf [ MAXRECV + 1 ];

s = "";

memset ( buf, 0, MAXRECV + 1 );

int status = ::recv ( m_sock, buf, MAXRECV, 0 );

if ( status == -1 )

{

cout <

return 0;

}

else if ( status == 0 )

{

return 0;

}

else

{

s = buf;

return status;

}

}

bool Socket::connect ( const string host, const int port )

{

if ( ! is_valid() ) return false;

m_addr.sin_family = AF_INET;

m_addr.sin_port = htons ( port );

int status = inet_pton ( AF_INET, host.c_str(), &m_addr.sin_addr );

if ( errno == EAFNOSUPPORT ) return false;

status = ::connect ( m_sock, ( sockaddr * ) &m_addr, sizeof ( m_addr ) );

if ( status == 0 )

return true;

else

return false;

}

void Socket::set_non_blocking ( const bool b )

{

int opts;

opts = fcntl ( m_sock,

F_GETFL );

if ( opts 

{

return;

}

if ( b )

opts = ( opts | O_NONBLOCK );

else

opts = ( opts & ~O_NONBLOCK );

fcntl ( m_sock,

F_SETFL,opts );

}

ServerSocket.h

// Definition of the ServerSocket class

#ifndef ServerSocket_class

#define ServerSocket_class

#include "Socket.h"

class ServerSocket : private Socket

{

public:

ServerSocket ( int port );

ServerSocket (){};

virtual ~ServerSocket();

const ServerSocket& operator <

const ServerSocket& operator >> ( std::string& ) const;

void accept ( ServerSocket& );

};

#endif

ServerSocket.cpp

// Implementation of the ServerSocket class

#include "ServerSocket.h"

#include "SocketException.h"

ServerSocket::ServerSocket ( int port )

{

if ( ! Socket::create() )

{

throw SocketException ( "Could not create server socket." );

}

if ( ! Socket::bind ( port ) )

{

throw SocketException ( "Could not bind to port." );

}

if ( ! Socket::listen() )

{

throw SocketException ( "Could not listen to socket." );

}

}

ServerSocket::~ServerSocket()

{

}

const ServerSocket& ServerSocket::operator <

{

if ( ! Socket::send ( s ) )

{

throw SocketException ( "Could not write to socket." );

}

return *this;

}

const ServerSocket& ServerSocket::operator >> ( std::string& s ) const

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值