Question

I am trying to send my port number to a function as const char *. The memory address on receiving is out of range. Can someone tel me what is the correct way of doing this ?

This is my code

Inside main()

     socket_open("host", 12345); // host and port number

On function side

     socket_open(char * host,int port) {
     int error;
     struct addrinfo hints;
     struct addrinfo *res;
     ...
     error = getaddrinfo(host,(char *)port,&hints,&res); 

I get a segmentation on getaddrinfo. 12345 is too big for char* it seems. How should i fix this ??

Was it helpful?

Solution

If getaddrinfo is expecting a string you must convert port (an int) to one first. Here is one way:

char portStr[MAX_PORT_STR_LEN];
snprintf(portStr, MAX_PORT_STR_LEN, "%d", port);

Now you can send it to getaddrinfo:

error = getaddrinfo(host, portStr, &hints, &res);

OTHER TIPS

I believe port should really be a character representation of the port based on what the documentation says here http://pubs.opengroup.org/onlinepubs/009695399/functions/getaddrinfo.html

char szPort[20];
sprintf(szPort, "%d", port);

You have an int in parameter port. Then you pass it to a function that interprets it as a character pointer, and starts reading characters from the address in the int until a zero is found. But the address points out of your readable memory segment. Or if no zero is found, it keeps reading until you get a segmentation fault.

Convert your number properly into a string.

See @Raz Wilson's answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top