unsigned char tmpBuf[DIAG_NOTIFY_LEN] = {0}; unsigned short usCrc = 0, uslen = 0; memset(tmpBuf, 0, DIAG_NOTIFY_LEN); ((NotifyHeader *)(tmpBuf))->HeaderFlag = htons(DIAG_MSG_HEADER); ((NotifyHeader *)(tmpBuf))->MsgType = htons(DIAG_NOTIFY_MSG); ((NotifyHeader *)(tmpBuf))->SeqNum = htons(g_usLastSeq); ((NotifyHeader *)(tmpBuf))->DataLen = htons(strlen(macBuf)); sprintf(tmpBuf+sizeof(NotifyHeader), "%s", macBuf); uslen = sizeof(NotifyHeader) + strlen(macBuf); usCrc = CRC16(tmpBuf, uslen); *(tmpBuf+uslen) = (usCrc & 0xff00) >> 8; *(tmpBuf+uslen+1) = usCrc & 0x00ff; if(0 > sendto(g_diagSockFd, tmpBuf, uslen+DIAG_CRC_LEN, 0, g_pstAddrInfo->ai_addr, g_pstAddrInfo->ai_addrlen)) { perror("diag_notify [sendto]"); }
typedef struct tagNotifyHeader { unsigned short HeaderFlag; unsigned short MsgType; unsigned short SeqNum; unsigned short DataLen; }NotifyHeader;考虑到字节对齐问题,定义时特意注意了一下保证数据结构的字节对齐。
*tmpBuf = (DIAG_MSG_HEADER & 0xFF00) >> 8; *(tmpBuf+1) = DIAG_MSG_HEADER & 0x00FF; ......结果问题依旧存在,后来想到全部转换为字符串的方式传输(如下),结果服务器端接收ok。
unsigned char tmpBuf[DIAG_NOTIFY_LEN] = {0}; unsigned short usCrc = 0, uslen = 0; memset(tmpBuf, 0, DIAG_NOTIFY_LEN); uslen = sprintf(tmpBuf, "%x", DIAG_MSG_HEADER); uslen += sprintf(tmpBuf+uslen, "%x", DIAG_NOTIFY_MSG); uslen += sprintf(tmpBuf+uslen, "%4x", g_usLastSeq); uslen += sprintf(tmpBuf+uslen, "%4x", strlen(macBuf)); uslen += sprintf(tmpBuf+uslen, "%s", macBuf); usCrc = CRC16(tmpBuf, uslen); uslen += sprintf(tmpBuf+uslen, "%4x", usCrc); if(0 > sendto(g_diagSockFd, tmpBuf, uslen, 0, g_pstAddrInfo->ai_addr, g_pstAddrInfo->ai_addrlen)) { perror("diag_notify [sendto]"); }结果问题虽然不出现了,但是原因没有找到,目前怀疑会不会与字符集有关。
原文地址:http://blog.csdn.net/qq2012qiao/article/details/40684961