# Trying to pass a string to a C network function



## caesius (Feb 1, 2010)

[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:


```
socket = tcp_connect("10.1.1.4", "1666");
```
Where the desired server and port are passed to tcp_connect.

Here's the 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.


----------



## expl (Feb 1, 2010)

caesius said:
			
		

> 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.



What do you mean by "has no idea how far they extend into memory"? Strings are null terminated, thats how functions know (including strlen).


----------



## qsecofr (Feb 1, 2010)

*IP and port*

Not sure if this helpful or the direction you want to take it, but in the past I had done something similar on a different OS using integers.  Port number is an integer.  Dotted decimal can be converted to an integer by a library function..

I'm not looking at the include file or the prototype to getaddrinfo(), but parm 3 looks like an address of a struct, while parm 4 looks like it is an address of a pointer to a struct.  If that's intentional and conforms to the prototype, then nevermind.


----------

