Click to See Complete Forum and Search --> : Why can't I pass a char* to innet_addr?


Anchoa23
November 3rd, 2009, 12:27 PM
Hi there!

I'm writing a code that will make connections with different servers and I need to create a socket for each of them. The problem arises when I initialize the SOCKADDR_IN sockAddr struct when I try the connect function. More specifically, when I use:

sockAddr.sin_addr.s_addr = inet_addr(_ipBOARD);

where char* _ipBOARD is defined in my program when read from a config file. When I try this, inet_addr returns -1, but if I try sockAddr.sin_addr.s_addr = inet_addr("173.20.20.199"); there is no prob. I checked the _ipBOARD and it is initialized to the correct IP.

Any clue?

Thanks a lot in advance!

hoxsiew
November 3rd, 2009, 02:46 PM
Hard to tell without some code. Is _ipBOARD NULL terminated?

0xC0000005
November 3rd, 2009, 03:45 PM
Do you know how to use Help or MSDN? This is what they say about the return value of inet_addr. INADDR_NONE is defined as 0xffffffff which is most likely what you are reporting as -1:

Return Value

If no error occurs, the inet_addr function returns an unsigned long value containing a suitable binary representation of the Internet address given.

If the string in the cp parameter does not contain a legitimate Internet address, for example if a portion of an "a.b.c.d" address exceeds 255, then inet_addr returns the value INADDR_NONE.

On Windows Server 2003 and later if the string in the cp parameter is an empty string, then inet_addr returns the value INADDR_NONE. If NULL is passed in the cp parameter, then inet_addr returns the value INADDR_NONE.

On Windows XP and earlier if the string in the cp parameter is an empty string, then inet_addr returns the value INADDR_ANY. If NULL is passed in the cp parameter, then inet_addr returns the value INADDR_NONE.

Also, do you know how to use the debugger to stop just before calling inet_addr() and examine the actual value held by your string?

Anchoa23
November 5th, 2009, 09:05 AM
Thanks for your help. Yep, I used msdn and everything and then I discovered (I'm not used to programming c++ with pointers) that I wasn't working correctly with my char*.

At first I declared it in my CSocket constructor as a char* _ipBoard, later on I assigned it as _ipBoard = ipBoard (read from a config file) and when I tried to use it for the connect() I noticed my _ipBoard contained nothing at all. So I changed the declaration to char _ipBoard[50], used the strncpy to copy it to the other array (ipBoard), and now everything works fine.

Thanks a lot anyway!