#include "basesocket"

void Basesocket::bind(string const &addr, int port) {
    // Make socket reusable.
    int val = 1;
    if (setsockopt (fd(), SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val))) {
	ostringstream o;
	o << "Failed to set reuse socket options on fd " << fd()
	  << ": " << strerror(errno);
	throw Error(o.str());
    }

    // Prepare binding.
    struct sockaddr_in saddr;
    memset (&saddr, 0, sizeof(saddr));
    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(port);

    // Assign interface to listen to
    if (addr[0] != '0') {
        debugmsg ("Binding socket " << fd() << " to specific IP address " <<
		  addr << '\n');
        if ( (saddr.sin_addr.s_addr = inet_addr (addr.c_str())) ==
	     INADDR_NONE )
            throw Error("Cannot convert IP " + addr + " to network bytes");
    } else {
        debugmsg ("Binding socket " << fd() << " to all local IP addresses\n");
        saddr.sin_addr.s_addr = htonl (INADDR_ANY);
    }
    
    // Bind and listen
    if (::bind (fd(), (sockaddr*) &saddr, sizeof(saddr)) < 0)
        throw Error(string("Failed to bind to IP/port: ") + strerror(errno));
    if (listen (fd(), 5) < 0)
	throw Error(string("Failed to listen to IP/port: ")
		    + strerror(errno));
    msg("Listening for activity on fd " << fd() << '\n');
}

    
