我的项目中有一个Master(INCA工具),它包含一个A2l文件(它作为客户端中变量和地址的信息)。 Master将通过TCP层触发客户端(代码如下)。主要通过询问特定地址的变量值来触发客户端。 下面的代码作为我的项目中提供的一些API并解释了它的作用。
在Master(INCA)中加载文件后,它会询问变量的值并调用以下API来发送和接收特定IP地址和端口号的帧。但我得到一个错误:没有工作基地分配给设备。 错误:传输层失败,CEtasEthSocket :: connect:连接事件检查失败(10061 WSAGetLastError())
此API就像一个客户端。
// pBytes : data to be transmitted
// numBytes: number of bytes at pBytes
// the above two data will be take care automatically and later I will SEND via the specified port
void XcpApp_IpTransmit(uint16 port, Xcp_StatePtr8 pBytes, uint16 numBytes) // this function must transmit the specified byte on IP connection identified by port
{
WSADATA wsa;
SOCKET s;
uint8 bytes_recieved;
struct sockaddr_in server; // creating a socket address structure: structure contains ip address and port number
uint16 numTxBytes;
uint8* pChunkData;
uint16 chunkLen;
port = 18000;
numTxBytes = 1;
uint8 recv_data[100];
printf("Initializing Winsock\n");
if(WSAStartup(MAKEWORD(2,2), &wsa)!=0)
{
printf("Failed Error Code: %d", WSAGetLastError());
return 1;
}
printf("Initialised\n");
//CREATING a SOCKET
if ((s = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
printf("Could not Create Socket\n");
//return 0;
}
printf("Socket Created\n");
//Binding between the socket and ip address
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_family = AF_INET;
server.sin_port = htons(port);
//Connect to a remote server
if(connect(s, (struct sockaddr*)&server, sizeof(server))<0)
{
puts("Connect Error\n");
//return 1;
}
puts("Connected\n");
while (1)
{
//initally its waiting for the data to be received on the port s and stored in recv_data buffer of size 100
bytes_recieved = recv(s, recv_data, 100 ,0 );
recv_data[bytes_recieved] = '\0'; // reading till the end of the buffer
pChunkData = &recv_data;
chunkLen = 1 ;
//This is the given API, When ever the data is receives a frame on the IP port. I should call this function
XcpIp_RxCallback (chunkLen, *pChunkData, port); // original API is : void XcpIp_RxCallback (uint16 chunkLen, uint8* pChunkData, uint16 port);
// chunklen : number of bytes at pchunkdata
// pChunkData : received frame
// port : port number
printf("received data from Master %d\n", *pChunkData);
//sending data from client to the Master
send(s, pBytes, numBytes, 0); // explained in the begining
if (strcmp(pBytes, "q") != 0 && strcmp(pBytes, "Q") != 0)
send(s, pBytes, numBytes, 0);
else
{
send(s, pBytes, numBytes, 0);
XcpIp_TxCallback (port, numTxBytes);
closesocket(s);
WSACleanup();
break;
}
}
}
XcpIp_OnTcpCxnClosed(port); // this iS AN API given to close the TCP connection.
}
答案 0 :(得分:1)
如果您将请求的100个字节作为最大值读取,则此行recv_data[bytes_recieved] = '\0';
将失败。它将引发未定义的行为作为recv_data
边界的写作。
要解决此问题,请更改此行:
bytes_recieved = recv(s, recv_data, 100 , 0 );
是
bytes_recieved = recv(s, recv_data, sizeof(recv_data)-1, 0);