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 26 of file tcp_listen.c.

References addr_from_str(), addr_htos(), and mem_set().

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

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 26 of file tcp_connect.c.

References addr_from_str(), and mem_set().

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


Generated on Tue Jun 19 20:38:45 2007 for lucid by  doxygen 1.5.2