请教UDP发送函数sendto的使用问题
1个回答
展开全部
给你一段简单处理的代码,你参考一下:
C/C++ code
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
sockaddr_in sendAddr;
sendAddr.sin_family = AF_INET;
sendAddr.sin_addr.s_addr = INADDR_BROADCAST;
sendAddr.sin_port = htons(SDP_SERVER_PORT);
//组包头
CommunicateHeader header;
memset(&header, 0, sizeof(CommunicateHeader));
memcpy(&header.leadByte, "NVSP", sizeof(header.leadByte));
header.version = 0;
header.flag = 0;
header.sequense = 0;
header.dataLength =0;
header.cmmand = NVSP_UDP_DEVICE;
header.result = 0;
UINT iCheckSum = nvspchecksum((UCHAR*)(&header), sizeof(CommunicateHeader));
SOCKET sendSocket = socket(AF_INET, SOCK_DGRAM, 0);
if(INVALID_SOCKET == m_sdpSendSocket)
{
AfxMessageBox(_T("创建SOCKET失败!"));
return;
}
BOOL optval;
lRet=setsockopt(sendSocket, SOL_SOCKET, SO_BROADCAST, (LPSTR)&optval, sizeof(optval));//设定为广播形式
if(-1==lRet)
{
AfxMessageBox(_T("SOCKET选项设置失败!"));
return;
}
UINT bufferSize = sizeof(CommunicateHeader) + 4;
char* sendPacket = new char[bufferSize];
memcpy(sendPacket, &header, sizeof(CommunicateHeader));
memcpy(sendPacket + sizeof(CommunicateHeader), &iCheckSum, sizeof(iCheckSum));
long lBytesSend = sendto(sendSocket, (char*)sendPacket, bufferSize, 0, (LPSOCKADDR)&sendAddr,sizeof(sendAddr));
if (lBytesSend != bufferSize)
{
AfxMessageBox(_T("发送数据失败!"));
return -1;
}
delete []sendPacket;
C/C++ code
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
sockaddr_in sendAddr;
sendAddr.sin_family = AF_INET;
sendAddr.sin_addr.s_addr = INADDR_BROADCAST;
sendAddr.sin_port = htons(SDP_SERVER_PORT);
//组包头
CommunicateHeader header;
memset(&header, 0, sizeof(CommunicateHeader));
memcpy(&header.leadByte, "NVSP", sizeof(header.leadByte));
header.version = 0;
header.flag = 0;
header.sequense = 0;
header.dataLength =0;
header.cmmand = NVSP_UDP_DEVICE;
header.result = 0;
UINT iCheckSum = nvspchecksum((UCHAR*)(&header), sizeof(CommunicateHeader));
SOCKET sendSocket = socket(AF_INET, SOCK_DGRAM, 0);
if(INVALID_SOCKET == m_sdpSendSocket)
{
AfxMessageBox(_T("创建SOCKET失败!"));
return;
}
BOOL optval;
lRet=setsockopt(sendSocket, SOL_SOCKET, SO_BROADCAST, (LPSTR)&optval, sizeof(optval));//设定为广播形式
if(-1==lRet)
{
AfxMessageBox(_T("SOCKET选项设置失败!"));
return;
}
UINT bufferSize = sizeof(CommunicateHeader) + 4;
char* sendPacket = new char[bufferSize];
memcpy(sendPacket, &header, sizeof(CommunicateHeader));
memcpy(sendPacket + sizeof(CommunicateHeader), &iCheckSum, sizeof(iCheckSum));
long lBytesSend = sendto(sendSocket, (char*)sendPacket, bufferSize, 0, (LPSOCKADDR)&sendAddr,sizeof(sendAddr));
if (lBytesSend != bufferSize)
{
AfxMessageBox(_T("发送数据失败!"));
return -1;
}
delete []sendPacket;
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询