#include "stdafx.h"
#include "UDP.h"
#include "CDV.h"
#include <WS2tcpip.h>
#include <iphlpapi.h>
#pragma comment(lib, "iphlpapi.lib")
UDP::UDP()
{
m_connectSocket = INVALID_SOCKET;
}
UDP::~UDP()
{
CloseConnect();
}
UDP::UDP(u_short port)
{
m_connectSocket = INVALID_SOCKET;
if (-1 == ConnectServerBC(port))
delete this;
}
int UDP::ConnectServerBC(u_short port)
{
//return ConnectServer(ip, strtoul(port, NULL, 10));
CloseConnect();
WSADATA wsaData;
struct addrinfo *result = NULL,
*ptr = NULL,
hints;
int iResult;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
::AfxMessageBox(_T("网络连接失败"), MB_ICONWARNING, TRUE);
return -1;
}
m_ip = "255.255.255.255";
m_port.Format("%d", port);
m_connectSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (m_connectSocket == INVALID_SOCKET) {
WSACleanup();
return -1;
}
const int opt = -1;
int nb = 0;
nb = setsockopt(m_connectSocket, SOL_SOCKET, SO_BROADCAST, (char*)&opt, sizeof(opt));
if (nb == -1)
{
return -1;
}
if (m_connectSocket == INVALID_SOCKET) {
WSACleanup();
//::AfxMessageBox(_T("网络连接失败"), MB_ICONWARNING, TRUE);
return -1;
}
//::AfxMessageBox(_T("恭喜,网络连接成功!"), MB_ICONWARNING, TRUE);
return 0;
}
int UDP::CloseConnect()
{
if (m_connectSocket == INVALID_SOCKET)
return 0;
int iResult = closesocket(m_connectSocket);
if (iResult == SOCKET_ERROR) {
//wprintf(L"关闭网络出错: %d\n", WSAGetLastError());
WSACleanup();
return -1;
}
// Clean up and quit.
WSACleanup();
return 0;
}
//只用于本地局域网查询npc
int UDP::BCSearch(char * sbuf, int slen, CStringArray &rarray, int rTimeout)
{
ASSERT(sbuf && slen);
int ret = -1;
char rbuf[200] = { 0 };
int rlen = 200;
if (m_connectSocket == INVALID_SOCKET)
return -1;
rarray.RemoveAll();
sockaddr_in senderAddr, destAddr, sourAddr;
/*设置源地址为本地广播地址*/
//bzero(&sourAddr, sizeof(struct sockaddr_in));
sourAddr.sin_family = AF_INET;
sourAddr.sin_addr.s_addr = htonl(INADDR_BROADCAST);
sourAddr.sin_port = htons(10);
//destAddr.sin_family = AF_INET;
//destAddr.sin_addr.s_addr = htonl(INADDR_ANY);
//destAddr.sin_port = htons(10);
int addrSize = sizeof(destAddr);
int iResult;
iResult = sendto(m_connectSocket, sbuf, slen, 0, (SOCKADDR *)& sourAddr, sizeof(sourAddr));
if (iResult == SOCKET_ERROR) {
return -1;
}
int timeout = rTimeout;
ret = setsockopt(m_connectSocket, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout));
do {
iResult = recvfrom(m_connectSocket, rbuf, rlen, 0, (SOCKADDR *)& destAddr, &addrSize);
int error = WSAGetLastError();
if (iResult > 0)
{
rarray.Add(rbuf);
}
else if (WSAETIMEDOUT == error)
{
return 0;
}
else
{
return -1;
}
} while (true);
}
mfc实现UDP通信
于 2023-03-13 10:54:22 首次发布