[Assorted-commits] SF.net SVN: assorted: [747] cpp-commons/trunk/src/commons/sockets.h
Brought to you by:
yangzhang
From: <yan...@us...> - 2008-05-08 19:31:48
|
Revision: 747 http://assorted.svn.sourceforge.net/assorted/?rev=747&view=rev Author: yangzhang Date: 2008-05-08 12:31:55 -0700 (Thu, 08 May 2008) Log Message: ----------- added basic sockets.h with just a tcp_listener Added Paths: ----------- cpp-commons/trunk/src/commons/sockets.h Added: cpp-commons/trunk/src/commons/sockets.h =================================================================== --- cpp-commons/trunk/src/commons/sockets.h (rev 0) +++ cpp-commons/trunk/src/commons/sockets.h 2008-05-08 19:31:55 UTC (rev 747) @@ -0,0 +1,53 @@ +#ifndef COMMONS_SOCKETS_H +#define COMMONS_SOCKETS_H + +#include <arpa/inet.h> +#include <netdb.h> +#include <netinet/in.h> +#include <strings.h> +#include <sys/socket.h> +#include <unistd.h> + +#include <commons/check.h> + +namespace commons +{ + + /** + * Create a listener socket, with SO_REUSEADDR. + * \param[in] port The port to listen on. + * \return The listener socket. + */ + int + tcp_listen(int port) + { + // Create the socket. + int sfd = checknneg(socket(PF_INET, SOCK_STREAM, 0)); + + try { + // Create the local socket address. + struct sockaddr_in sa; + bzero(&sa, sizeof(sa)); + sa.sin_family = AF_INET; + sa.sin_port = htons(port); + sa.sin_addr.s_addr = htonl(INADDR_ANY); + + // Configure the socket. + int n = 1; + check0x(setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (char *)&n, sizeof(n))); + + // Bind the socket to the local socket address. + check0x(bind(sfd, (struct sockaddr*) &sa, sizeof(struct sockaddr_in))); + + // Start listening. + check0x(listen(sfd, 256)); + + return sfd; + } catch (...) { + close(sfd); + throw; + } + } +} + +#endif This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |