TCP socket wrappers


Detailed Description

The tcp family of functions provide wrappers around connect(2) and listen(2) taking an IP address in the string pointed to by ip and the port number as arguments.


Functions

int tcp_listen (const char *ip, int port, int backlog)
 listen for incomming connections
int tcp_connect (const char *ip, int port)
 connect to TCP socket


Function Documentation

int tcp_listen ( const char *  ip,
int  port,
int  backlog 
)

listen for incomming connections

Parameters:
ip IP to listen on
port port to listen on
backlog queue backlog
Returns:
filedescriptor for the newly allocated socket, -1 on error with errno set

Definition at line 27 of file tcp_listen.c.

References addr_from_str(), and str_zero().

00028 {
00029         int fd;
00030         struct sockaddr_in inaddr;
00031         
00032         if (port < 1)
00033                 return errno = EINVAL, -1;
00034         
00035         str_zero(&inaddr, sizeof(inaddr));
00036         inaddr.sin_family = AF_INET;
00037         inaddr.sin_port   = htons(port);
00038         
00039         if (addr_from_str(ip, &inaddr.sin_addr.s_addr, 0) == 0)
00040                 return errno = EINVAL, -1;
00041         
00042         if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
00043                 return -1;
00044         
00045         if (bind(fd, (struct sockaddr *) &inaddr, sizeof(struct sockaddr_in)) == -1) {
00046                 close(fd);
00047                 return -1;
00048         }
00049         
00050         if (listen(fd, backlog) == -1) {
00051                 close(fd);
00052                 return -1;
00053         }
00054         
00055         return fd;
00056 }

int tcp_connect ( const char *  ip,
int  port 
)

connect to TCP socket

Parameters:
ip IP to connect to
port port to connect to
Returns:
filedescriptor for the newly allocated connection, -1 on error with errno set

Definition at line 27 of file tcp_connect.c.

References addr_from_str(), and str_zero().

00028 {
00029         int fd;
00030         struct sockaddr_in inaddr;
00031         
00032         if (port < 1)
00033                 return errno = EINVAL, -1;
00034         
00035         str_zero(&inaddr, sizeof(inaddr));
00036         inaddr.sin_family = AF_INET;
00037         inaddr.sin_port   = htons(port);
00038         
00039         if (addr_from_str(ip, &inaddr.sin_addr.s_addr, 0) == 0)
00040                 return errno = EINVAL, -1;
00041         
00042         if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
00043                 return -1;
00044         
00045         if (connect(fd, (struct sockaddr *) &inaddr, sizeof(struct sockaddr_in)) == -1) {
00046                 close(fd);
00047                 return -1;
00048         }
00049         
00050         return fd;
00051 }


Generated on Sun Dec 3 17:46:16 2006 for lucid by  doxygen 1.5.1