Hello, there was a problem, I can not transfer data on the socket, namely, unsigned int array. Swears on the 39th line, writes:

[C++ Error] KlientUDP.cpp(39): E2034 Cannot convert 'unsigned int *' to 'const char *' [C++ Error] KlientUDP.cpp(39): E2342 Type mismatch in parameter 'buf' (wanted 'const char *', got 'unsigned int *') 

Char array is transmitted without problems, but it does not work out. Help please, find errors, I recently met with sockets, I may not know something basic. In general, I will be glad to every answer.

Here is the client code

 //--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "KlientUDP.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TForm1 *Form1; //--------------------------------------------------------------------------- __fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) { const int iReqWinsockVer = 2; WSADATA wsaData; if (WSAStartup(iReqWinsockVer,&wsaData)==0) { ShowMessage("Π˜Π½ΠΈΡ†ΠΈΠ°Π»ΠΈΠ·Π°Ρ†ΠΈΡ Π±ΠΈΠ±Π»ΠΈΠΎΡ‚Π΅ΠΊΠΈ сокСта(Ws2_32.dll) ΡƒΠ΄Π°Π»Π°ΡΡŒ"); SOCKET s; s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (s == INVALID_SOCKET) ShowMessage("ΠŸΡ€ΠΈ создании сокСта Π²ΠΎΠ·Π½ΠΈΠΊΠ»Π° ошибка"); else ShowMessage("Π‘ΠΎΠ·Π΄Π°Π½ΠΈΠ΅ сокСта Π±Ρ‹Π»ΠΎ ΡƒΡΠΏΠ΅ΡˆΠ½Ρ‹ΠΌ!"); sockaddr_in sockAddr; sockAddr.sin_family = AF_INET; sockAddr.sin_port = htons(80); sockAddr.sin_addr.S_un.S_addr = inet_addr("169.254.128.135"); unsigned int buf[20]; buf[0] = 3; while(true) { sendto(s, buf, sizeof(buf), 0, (struct sockaddr *)&sockAddr, sizeof(sockAddr)); } closesocket(s); if (WSACleanup()!=0) ShowMessage("ОсвобоТдСниС рСсурсов WinSock Π½Π΅ ΡƒΠ΄Π°Π»ΠΎΡΡŒ"); else ShowMessage("ОсвобоТдСниС рСсурсов WinSock Π·Π°Π²Π΅Ρ€ΡˆΠΈΠ»ΠΎΡΡŒ успСхом"); } else ShowMessage("Π˜Π½ΠΈΡ†ΠΈΠ°Π»ΠΈΠ·Π°Ρ†ΠΈΡ Π±ΠΈΠ±Π»ΠΈΠΎΡ‚Π΅ΠΊΠΈ сокСта(Ws2_32.dll) Π½Π΅ ΡƒΠ΄Π°Π»Π°ΡΡŒ"); } 
  • 2
    ..., (const char*)buf, ... - user194374

1 answer 1

sendto accepts const char* , what is inside - it does not matter if only the dimensions converge, therefore:

 sendto(s, (const char*)buf, sizeof(buf), 0, (struct sockaddr *)&sockAddr, sizeof(sockAddr)); 
  • "sizeof (buf [0]) * sizeof (buf)" how many will give for 20 int? - Vladimir Martyanov
  • corrected, thanks - Vasfed
  • To clarify: First convert int to const char. And since char occupies 1 byte in memory (int 4 bytes), we multiply the array (20 elements) by buf [0] (that is, by 4). To stop why it is unclear why multiply? Can you explain? After all, all the elements will be transferred? - WFZ
  • It is not necessary to multiply, sizeof (buf) and so will return the desired size (btw, not necessarily 80 bytes, depends on the architecture). In general, the order of bytes inside the int itself on the receiver and receiver must be taken into account - Vasfed