Search code examples
c++textboxip-addresswinsock

c++ winsock client cannot connect using textbox for host IP


I cannot get it connect to my server when i use the host IP from my textbox. See my code :

                    char *bufhost;
                int bufhostlen;
                bufhostlen = GetWindowTextLength(hwndTextBox_ip) + 1;
                GetWindowText(hwndTextBox_ip, bufhost, bufhostlen);
                sockaddr_in sin;
                sin.sin_family=AF_INET;
                sin.sin_port=htons(5060);
                sin.sin_addr.s_addr=inet_addr(bufhost);
                connect(sock,(LPSOCKADDR)(&sin),sizeof(sin));

If i use

sin.sin_addr.s_addr=inet_addr("127.0.0.1");

It connects without problem.

I really don't know how to get this work (searched for hours...) Thanks for helping :-)

SOLUTION :

as PermanentGuest told me, i have to allocate memory to my buffer :

                    char *bufhost;
                int bufhostlen;
                bufhostlen = GetWindowTextLength(hwndTextBox_ip) + 1;
                bufhost = (char*) malloc(bufhostlen);
                GetWindowText(hwndTextBox_ip, bufhost, bufhostlen);
                sockaddr_in sin;
                sin.sin_family=AF_INET;
                sin.sin_port=htons(5060);
                sin.sin_addr.s_addr=inet_addr(bufhost);
                connect(sock,(LPSOCKADDR)(&sin),sizeof(sin));

Solution

  • You need to allocate memory for bufhost. Unfortunateley the documentation of GetWindowText doesn't mention this explicitly. However for all win32 APIs, this is the common behaviour