本文整理汇总了C++中SockAddr类的典型用法代码示例。如果您正苦于以下问题:C++ SockAddr类的具体用法?C++ SockAddr怎么用?C++ SockAddr使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SockAddr类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: throw
ssize_t
UDPInetSocket::recvfrom(SockAddr &from, void *buf, size_t count,
int flags) throw()
{
union {
sockaddr base;
sockaddr_in ipv4;
sockaddr_in6 ipv6;
} u;
socklen_t addrLen = sizeof(u);
ssize_t read = ::recvfrom(sock, buf, count, flags, &u.base, &addrLen);
if (read != -1) {
switch (u.base.sa_family) {
case AF_INET:
from.setAddr(u.ipv4);
break;
case AF_INET6:
from.setAddr(u.ipv6);
break;
default:
read = -1;
errno = ENOMSG;
break;
}
}
return read;
}
示例2: SockAddr
bool MiniWebServer::init(const string &ip, int _port) {
port = _port;
SockAddr me;
if ( ip.empty() )
me = SockAddr( port );
else
me = SockAddr( ip.c_str(), port );
sock = ::socket(me.family, SOCK_STREAM, 0);
if ( sock == INVALID_SOCKET ) {
log() << "ERROR: MiniWebServer listen(): invalid socket? " << errno << endl;
return false;
}
prebindOptions( sock );
if ( ::bind(sock, me.getSockAddr(), me.addressSize) != 0 ) {
log() << "MiniWebServer: bind() failed port:" << port << " errno:" << errno << endl;
if ( errno == 98 )
log() << "98 == addr already in use" << endl;
closesocket(sock);
return false;
}
if ( ::listen(sock, 16) != 0 ) {
log() << "MiniWebServer: listen() failed " << errno << endl;
closesocket(sock);
return false;
}
return true;
}
示例3: if
bool SockAddr::operator<(const SockAddr& r) const {
if (getType() < r.getType())
return true;
else if (getType() > r.getType())
return false;
if (getPort() < r.getPort())
return true;
else if (getPort() > r.getPort())
return false;
switch (getType()) {
case AF_INET:
return as<sockaddr_in>().sin_addr.s_addr < r.as<sockaddr_in>().sin_addr.s_addr;
case AF_INET6:
return memcmp(as<sockaddr_in6>().sin6_addr.s6_addr,
r.as<sockaddr_in6>().sin6_addr.s6_addr,
sizeof(in6_addr)) < 0;
case AF_UNIX:
return strcmp(as<sockaddr_un>().sun_path, r.as<sockaddr_un>().sun_path) < 0;
case AF_UNSPEC:
return false;
default:
massert(SOCK_FAMILY_UNKNOWN_ERROR, "unsupported address family", false);
}
return false;
}
示例4: CountIP
void ExternalIPCounter::CountIP( const SockAddr& addr, int weight ) {
// ignore anyone who claims our external IP is
// INADDR_ANY or on a local network
if(addr.is_addr_any() || is_ip_local(addr))
return;
// timestamp the first time we get a vote
if(! _HeatStarted)
_HeatStarted = time(NULL);
// attempt to insert this vote
std::pair<candidate_map::iterator, bool> inserted = _map.insert(std::make_pair(addr, weight));
// if the new IP wasn't inserted, it's already in there
// increase the vote counter
if (!inserted.second)
inserted.first->second += weight;
// if the IP vout count exceeds the current leader, replace it
if(addr.isv4() && (_winnerV4 == _map.end() || inserted.first->second > _winnerV4->second))
_winnerV4 = inserted.first;
if(addr.isv6() && (_winnerV6 == _map.end() || inserted.first->second > _winnerV6->second))
_winnerV6 = inserted.first;
_TotalVotes += weight;
Rotate();
}
示例5: random_address
SockAddr random_address() {
SockAddr ret;
memset(ret._in._in6, 0, 16);
for (int i = 12; i < 16; ++i) {
ret._in._in6[i] = rand() & 0xff;
}
ret.set_port((rand() % 1000) + 1024);
return ret;
}
示例6: getLocalAddrForBoundSocketFd
static SockAddr getLocalAddrForBoundSocketFd(int fd) {
SockAddr result;
int rc = getsockname(fd, result.raw(), &result.addressSize);
if (rc != 0) {
warning() << "Could not resolve local address for socket with fd " << fd << ": " <<
getAddrInfoStrError(socketGetLastError());
result = SockAddr();
}
return result;
}
示例7: getIpPortFromSockAddr
IpPort getIpPortFromSockAddr(const SockAddr &sa){
const int family = sa.getFamily();
if(family == AF_INET){
if(sa.getSize() < sizeof(::sockaddr_in)){
LOG_POSEIDON_WARNING("Invalid IPv4 SockAddr: size = ", sa.getSize());
DEBUG_THROW(Exception, sslit("Invalid IPv4 SockAddr"));
}
char ip[INET_ADDRSTRLEN];
const char *const str = ::inet_ntop(AF_INET,
&static_cast<const ::sockaddr_in *>(sa.getData())->sin_addr, ip, sizeof(ip));
if(!str){
DEBUG_THROW(SystemException);
}
return IpPort(SharedNts(str),
loadBe(static_cast<const ::sockaddr_in *>(sa.getData())->sin_port));
} else if(family == AF_INET6){
if(sa.getSize() < sizeof(::sockaddr_in6)){
LOG_POSEIDON_WARNING("Invalid IPv6 SockAddr: size = ", sa.getSize());
DEBUG_THROW(Exception, sslit("Invalid IPv6 SockAddr"));
}
char ip[INET6_ADDRSTRLEN];
const char *const str = ::inet_ntop(AF_INET6,
&static_cast<const ::sockaddr_in6 *>(sa.getData())->sin6_addr, ip, sizeof(ip));
if(!str){
DEBUG_THROW(SystemException);
}
return IpPort(SharedNts(str),
loadBe(static_cast<const ::sockaddr_in6 *>(sa.getData())->sin6_port));
}
LOG_POSEIDON_WARNING("Unknown IP protocol ", family);
DEBUG_THROW(Exception, sslit("Unknown IP protocol"));
}
示例8: RETURN_NET_ERROR_WITH
bool UdpEndPoint::open(const SockAddr& sockaddr,
int backlog,
auto_ptr<base::net::HandlerCreatorStrategyBase> handler_stg,
auto_ptr<base::net::FilterCreatorStrategyBase> sp_filter_stg,
ErrorCode* ec)
{
int fd = ::socket(sockaddr.getType(), SOCK_DGRAM, 0);
if (-1 == fd)
RETURN_NET_ERROR_WITH(ec, errno, "addr=" << sockaddr, false);
ScopedFD spfd(fd);
if (sockaddr.getType() == AF_UNIX)
{
const sockaddr_un& un = sockaddr.as<sockaddr_un>();
unlink(un.sun_path); // in case it already exists
}
SocketHelper::setNonBlocking(fd, ec);
SocketHelper::setReusable(fd, ec);
if (-1 == ::bind(fd, sockaddr.raw(), sockaddr.size()))
RETURN_NET_ERROR_WITH(ec, errno, "addr=" << sockaddr, false);
boost::shared_ptr<Handler> newhandler;
if (0 == sockaddr.getPort())
{
struct sockaddr_in addr;
socklen_t len = sizeof(addr);
if (-1 == getsockname(fd, (struct sockaddr *)&addr, &len))
RETURN_NET_ERROR_WITH(ec, errno, "", false);
SockAddr setaddr(ntohs(addr.sin_port));
handler_stg->create(fd, setaddr, sp_reactor_impl_, newhandler);
}
else
handler_stg->create(fd, sockaddr, sp_reactor_impl_, newhandler);
if (!newhandler)
RETURN_NET_ERROR_WITH(ec, errno, "create handler failed" << sockaddr, false);
newhandler->setConnected();
if (sp_filter_stg.get())
newhandler->setFilter(auto_ptr<Filter>(sp_filter_stg->create(false, newhandler.get())));
HandlerScoper<Handler> handler_scoper(newhandler);
spfd.release();
if (!sp_reactor_impl_->registerHandler(newhandler, MASK_READ, ec))
return false;
handler_scoper.release();
setUdpHandler(newhandler);
return true;
}
示例9: sendto
//-----------------------------------------------------------------------
//
//-----------------------------------------------------------------------
size_t SocketOStream::sendto (const void* buf, const size_t size, const SockAddr& dstAddr)
throw (IOException)
{
ssize_t result;
result = ::sendto (m_fd, buf, size, 0, &(dstAddr.getSockaddr()), dstAddr.getSockaddrLen());
if (result == -1)
throw IOException (errno);
return result;
}
示例10: onConnection
void TcpServer::onConnection(int connfd, const SockAddr& peerAddr)
{
EventLoop* ioLoop = loopThreadPool_.getNextLoop();
if (!ioLoop) ioLoop = loop_;
TcpConnectionPtr conn(new TcpConnection(ioLoop, connfd, peerAddr, ++connectionId_));
conn->setCloseCallback(simex::bind(&TcpServer::onClose, this, _1));
conn->setMessageCallback(messageCallback_);
LOG_TRACE("new client|ip=%s|port=%u", peerAddr.ip().c_str(), peerAddr.port());
connectionManager_->Add(conn->id(), conn);
conn->run();
if (connectionCallback_) connectionCallback_(conn);
}
示例11: connect
bool Socket::connect(SockAddr& remote) {
_remote = remote;
_fd = socket(remote.getType(), SOCK_STREAM, 0);
if ( _fd == INVALID_SOCKET ) {
LOG(_logLevel) << "ERROR: connect invalid socket " << errnoWithDescription() << endl;
return false;
}
if ( _timeout > 0 ) {
setTimeout( _timeout );
}
static const unsigned int connectTimeoutMillis = 5000;
ConnectBG bg(_fd, remote);
bg.go();
if ( bg.wait(connectTimeoutMillis) ) {
if ( bg.inError() ) {
warning() << "Failed to connect to "
<< _remote.getAddr() << ":" << _remote.getPort()
<< ", reason: " << bg.getErrnoWithDescription() << endl;
close();
return false;
}
}
else {
// time out the connect
close();
bg.wait(); // so bg stays in scope until bg thread terminates
warning() << "Failed to connect to "
<< _remote.getAddr() << ":" << _remote.getPort()
<< " after " << connectTimeoutMillis << " milliseconds, giving up." << endl;
return false;
}
if (remote.getType() != AF_UNIX)
disableNagle(_fd);
#ifdef SO_NOSIGPIPE
// ignore SIGPIPE signals on osx, to avoid process exit
const int one = 1;
setsockopt( _fd , SOL_SOCKET, SO_NOSIGPIPE, &one, sizeof(int));
#endif
_local = getLocalAddrForBoundSocketFd(_fd);
_fdCreationMicroSec = curTimeMicros64();
_awaitingHandshake = false;
return true;
}
示例12: while
bool NetChannelBase::FlushStream()
{
bool bError = false;
while (m_StreamOut.GetSize() > 0)
{
int32 nLen = (int32)m_StreamOut.GetSize();
int32 nRet = m_socket.Send((char*)m_StreamOut.GetBufferStart(), nLen);
if( nRet < 0 )
{
int32 nError = Socket::GetSysError();
if( nError == MY_EWOULDBLOCK || nError == MY_EAGAIN )
break;
else if( nError == MY_ECONNRESET )
nRet = 0;
else
{
SockAddr addr;
m_socket.GetSockAddr(addr);
MyLog::error("[%s:%u] IO Error [%d] when sending data !", addr.GetIP().c_str(), addr.GetPort(), GetID(), nError);
DisConnect();
nError = true;
break;
}
}
if( nRet == 0 )
{
SockAddr addr;
m_socket.GetPeerAddr(addr);
MyLog::error("NetChannelBase::flushStream() [%s:%u][%u] connection is closed!", addr.GetIP().c_str(), addr.GetPort(), GetID());
DisConnect();
bError = true;
break;
}
m_pMgr->BytesSend().Add(nRet);
m_StreamOut.Remove(nRet);
m_nTotalSendByte += nRet;
if( nRet < nLen )
break;
}
return !bError;
}
示例13: open
bool Acceptor::open(const SockAddr& sockaddr,
int backlog,
auto_ptr<HandlerCreatorStrategyBase> handler_creator_stg,
auto_ptr<FilterCreatorStrategyBase> filter_stg,
ErrorCode* ec)
{
if (!handler_creator_stg.get())
RETURN_ERROR_WITH(ec, E_NET_CREATE_NEW_HANDLER_FAILED, "addr=" << sockaddr, false);
int fd = ::socket(sockaddr.getType(), SOCK_STREAM, 0);
if (-1 == fd)
RETURN_NET_ERROR_WITH(ec, errno, "addr=" << sockaddr, false);
ScopedFD spfd(fd);
if (sockaddr.getType() == AF_UNIX)
{
const sockaddr_un& un = sockaddr.as<sockaddr_un>();
unlink(un.sun_path); // in case it already exists
}
SocketHelper::setNonBlocking(fd, ec);
SocketHelper::setReusable(fd, ec);
if (flag_ & OPT_KEEPALIVE)
SocketHelper::setKeepAlive(fd, ec);
if (flag_ & OPT_NODELAY)
SocketHelper::disableNagle(fd, ec);
if (-1 == ::bind(fd, sockaddr.raw(), sockaddr.size()))
RETURN_NET_ERROR_WITH(ec, errno, "addr=" << sockaddr, false);
if (-1 == ::listen(fd, backlog))
RETURN_NET_ERROR_WITH(ec, errno, "addr=" << sockaddr, false);
boost::shared_ptr<Handler> newhandler;
newhandler.reset(new AcceptorHandler(fd, sockaddr, sp_reactor_impl_, handler_creator_stg, filter_stg));
HandlerScoper<Handler> handler_scoper(newhandler);
spfd.release();
if (!sp_reactor_impl_->registerHandler(newhandler, MASK_ACCEPT, ec))
return false;
LOG(info, "listen on "<< sockaddr);
handler_scoper.release();
setAcceptorHandler(newhandler);
return true;
}
示例14: switch
bool SockAddr::operator==(const SockAddr& r) const {
if (getType() != r.getType())
return false;
if (getPort() != r.getPort())
return false;
switch (getType()) {
case AF_INET: return as<sockaddr_in>().sin_addr.s_addr == r.as<sockaddr_in>().sin_addr.s_addr;
case AF_INET6: return memcmp(as<sockaddr_in6>().sin6_addr.s6_addr, r.as<sockaddr_in6>().sin6_addr.s6_addr, sizeof(in6_addr)) == 0;
case AF_UNIX: return strcmp(as<sockaddr_un>().sun_path, r.as<sockaddr_un>().sun_path) == 0;
case AF_UNSPEC: return true; // assume all unspecified addresses are the same
default: massert(SOCK_FAMILY_UNKNOWN_ERROR, "unsupported address family", false);
}
}
示例15: sizeof
SocketError SocketImpl::bind(const SockAddr& sockAddr) {
if (socket == INVALID_SOCKET) {
return SocketError::NotInitialized;
}
sockaddr_storage storage;
sockAddr.toNative(&storage);
// For bind we also want to set the SO_EXCLUSIVEADDRUSE option
DWORD opt = 1;
int optRes = ::setsockopt(socket, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&opt, sizeof(DWORD));
if (optRes != 0) {
return getSocketError(::WSAGetLastError());
}
int bindRes = ::bind(socket, (const sockaddr*)&storage, sizeof(sockaddr_storage));
if (bindRes != 0) {
return getSocketError(::WSAGetLastError());
}
// And then we need to fetch back the bound addr/port
int nameLen = sizeof(sockaddr_storage);
int nameRes = ::getsockname(socket, (sockaddr*)&storage, &nameLen);
if (nameRes != 0) {
return getSocketError(::WSAGetLastError());
}
localAddr = SockAddr::fromNative(&storage);
return SocketError::Ok;
}