[SOLVED] Couple of errors in my code - fixed now.
I'm getting sick of writing the same net code over and over so I finally decided to write a function, tcp_connect, to use in other projects.
It's usage meant to be something like:
Where the desired server and port are passed to tcp_connect.
Here's the code:
It compiles and runs... but not correctly. I'm not suprised, since I'm passing a pointer to the start of each string and the tcp_connect function has no idea how far they extend into memory.
What would be the recommended way to code this? So far all i can think of is passing strlen() of each string along with the strings themselves.
I'm getting sick of writing the same net code over and over so I finally decided to write a function, tcp_connect, to use in other projects.
It's usage meant to be something like:
Code:
socket = tcp_connect("10.1.1.4", "1666");
Here's the code:
Code:
#include "net.h"
/* Return a socket file descriptor or -1 on error */
int
tcp_connect(char *server, char *port)
{
struct addrinfo hints, *res, *p;
int sockfd;
int rv;
if ((rv = getaddrinfo(server, port, &hints, &res)) != 0)
{
fprintf(stderr, "error: %s\n", gai_strerror);
return -1;
}
for (p = res; p != NULL; p = p->ai_next)
{
if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) < 0)
{
perror("socket");
continue;
}
break;
}
if (p == NULL)
{
fprintf(stderr, "error: could not create socket\n");
return -1;
}
freeaddrinfo(res);
return sockfd;
}
It compiles and runs... but not correctly. I'm not suprised, since I'm passing a pointer to the start of each string and the tcp_connect function has no idea how far they extend into memory.
What would be the recommended way to code this? So far all i can think of is passing strlen() of each string along with the strings themselves.