This is me again :) There is such a function:

char* HtmlList(char html[]) { char headers[255]; char Content_Length[1024]; char result[1024]; sprintf(Content_Length, "Content-Length: %d\r\n", (char) strlen(html)); strcpy(headers, "HTTP/1.0 200 OK\r\n"); strcat(headers, "Content-Type: text/html\r\n"); strcat(headers, Content_Length); strcat(headers, "Connection: close\r\n\r\n"); strcat(headers, html); strcpy(result, headers); return result; } 

Well, I try to call her:

 void Main_WebServer() { SOCKET Winsock; char Buf[255]; //char* buffer; char Content_Length[1024]; char headers[255]; struct sockaddr_in client; int clientsize = sizeof(client); int s; char html[] = "<b>TEST!</b>"; *Buf = (char) HtmlList(html); Winsock = Start_Server(5656); listen(Winsock, 5); while (1) { s = accept(Winsock, (struct sockaddr*)&client, &clientsize); if (s == INVALID_SOCKET) break; send(s, Buf, (int)strlen(Buf), 0); } closesocket(Winsock); // закрытие сокета WSACleanup(); } 

It compiles without errors, but does not work. Instead of <b>TEST!</b> some characters when connected via netcat .

But if you put everything in one function, it works.

  • sprintf (Content_Length, "Content-Length:% d \ r \ n", (char) strlen (html)); strlen () cannot be reduced to char ; the result may become negative. - avp
  • Immediately did not notice: char result [1024]; ... return result; Serious mistake. You cannot return the address of a variable on the stack (automatic). The easiest way in your case is to make an int HtmlList (char html [], char * result_buf) into result_buf, which will put the result, and return its length (just for send ()). - avp

1 answer 1

And what function gives separately, without connections. As far as I understand, the matter is in the scope of variables. result ceases to exist as soon as we exit the function. And one more thing - why allocate memory for an array of characters for Buf, if you then use it as a pointer?

  • duck i'm learning) - or_die
  • I got what you mean. All here to study. =) You can pass a pointer to an array and its length as a function parameter, as already done with html. cyberguru.ru/programming/cpp/… - here you can see what I meant. - Stas Litvinenko