udp地址和端口重复绑定

int const	BUFF_LEN = 1024;
char		receiveBuff[BUFF_LEN] = { 0 };
int			nDataLen = 0;

SOCKADDR_IN	addrReceive;
addrReceive.sin_family = AF_INET;
addrReceive.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
addrReceive.sin_port = htons(nUdpPort);

SOCKADDR_IN	addrCur;
int    nSizeAddr = sizeof(addrCur);

//SO_REUSEADDR允许完全相同的地址和端口的重复绑定。但这只用于UDP的多播,不用于TCP。 
int nRecvBuf = 1;
int optret = setsockopt(pTouchDlg->m_udpThreadReceiveSocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&nRecvBuf, sizeof(int));//设置属性要多次调用,不可以取或,可能参数丢失。
setsockopt(pTouchDlg->m_udpThreadReceiveSocket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&nRecvBuf, sizeof(int));

if (optret != 0)
{
	return -1;
}

if (::bind(pTouchDlg->m_udpThreadReceiveSocket, (struct sockaddr *)&addrReceive, sizeof(addrReceive)) == SOCKET_ERROR)
{
	return -1;
}

while (true)
{
	nDataLen = recvfrom(pTouchDlg->m_udpThreadReceiveSocket, (char *)receiveBuff, BUFF_LEN, 0, (struct sockaddr *)&addrCur, &nSizeAddr);
	if (nDataLen != ERROR && nDataLen != -1)
	{
    //接收到的数据
    }
}

 

你可能感兴趣的:(C++)