// Version 0.2 // 15 December 2006 // Changelog: // Added polling support // Implementation of the Socket class. #include "socket.h" #include "string.h" #include #include #include #include Socket::Socket() : m_sock (-1) { memset ( &m_addr, 0, sizeof(m_addr) ); } Socket::~Socket() { if ( is_valid() ) ::close ( m_sock ); } bool Socket::createWithUDP() { m_sock = socket ( AF_INET, SOCK_DGRAM, 0 ); //fcntl(m_sock, F_SETFL, O_NONBLOCK); if ( ! is_valid() ) return false; // TIME_WAIT - argh int on = 1; if ( setsockopt ( m_sock, SOL_SOCKET, SO_REUSEADDR, (const char*) &on, sizeof (on) ) == -1 ) return false; return true; } bool Socket::bind ( const int port ) { if ( ! is_valid() ) return false; m_addr.sin_family = AF_INET; m_addr.sin_addr.s_addr = INADDR_ANY; m_addr.sin_port = htons ( port ); int bind_return = ::bind ( m_sock, ( struct sockaddr * ) &m_addr, sizeof ( m_addr ) ); if ( bind_return == -1 ) return false; return true; } bool Socket::setHost( const std::string hostName, const int port) { if( (he=gethostbyname(hostName.c_str())) == NULL ) { return false; } m_addr.sin_family = AF_INET; m_addr.sin_port = htons(port); m_addr.sin_addr = *( (struct in_addr *)he->h_addr ); memset( &(m_addr.sin_zero), '\0', 8); return true; } bool Socket::sendto ( const std::string s ) const { int status = ::sendto ( m_sock, s.c_str(), s.size(), 0, (struct sockaddr *) &m_addr, sizeof(struct sockaddr) ); if ( status == -1 ) return false; else return true; } // polls the buffer for messages // int poll(struct pollfd *ufds, unsigned int nfds, int timeout); // timeout is in milliseconds // function returns: // -1 on error // 0 on timeout // 1 on data ready to receive int Socket::checkBuffer() { struct pollfd ufds[1]; ufds[0].fd = m_sock; ufds[0].events = POLLIN; return poll(ufds, 1, 1500); } int Socket::recvfrom( std::string &s ) const { char buf [MAXRECV + 1]; s = ""; memset ( buf, 0, MAXRECV + 1 ); socklen_t addr_len; addr_len = sizeof(struct sockaddr); int status = ::recvfrom ( m_sock, buf, MAXRECV, 0, (struct sockaddr *) &m_addr, &addr_len ); if ( status == -1 ) { std::cout << "status == -1 errno == " << errno << " in Socket::recv\n"; return -1; } else if ( status == 0 ) { return 0; } else { //std::cout<< "buffer = " << buf << "\n"; //std::cout<< "status = " << s << std::endl; s = buf; return status; } }