77 lines
1.8 KiB
C++
77 lines
1.8 KiB
C++
// UDP.cpp: implementation of the CUDP class.
|
|
//
|
|
//////////////////////////////////////////////////////////////////////
|
|
#include "StdAfx.h"
|
|
#include "UDP.h"
|
|
//////////////////////////////////////////////////////////////////////
|
|
// Construction/Destruction
|
|
//////////////////////////////////////////////////////////////////////
|
|
|
|
CUDP::CUDP()
|
|
{
|
|
|
|
}
|
|
|
|
CUDP::~CUDP()
|
|
{
|
|
|
|
}
|
|
void CUDP::init()
|
|
{
|
|
WSAData wsd;
|
|
if (WSAStartup(MAKEWORD(2,2),&wsd)!=0)
|
|
{
|
|
WSACleanup();
|
|
exit(1);
|
|
}
|
|
if ((m_SocketSend=socket(AF_INET,SOCK_DGRAM,0))==-1)
|
|
{
|
|
perror("NetSocks Failed");
|
|
exit(0);
|
|
}
|
|
int optval=8;
|
|
if (setsockopt(m_SocketSend,IPPROTO_IP,SO_REUSEADDR,(char*)&optval,sizeof(int))==-1)
|
|
{
|
|
perror("setsockopt(IP_TTL)");
|
|
}
|
|
if ((m_SocketRecv=socket(AF_INET,SOCK_DGRAM,0))==-1)
|
|
{
|
|
perror("NetSocks Failed");
|
|
exit(0);
|
|
}
|
|
if (setsockopt(m_SocketRecv,IPPROTO_IP,SO_REUSEADDR,(char*)&optval,sizeof(int))==-1)
|
|
{
|
|
perror("setsockopt(IP_TTL)");
|
|
}
|
|
}
|
|
void CUDP::UDPSend(char buf[],int len,unsigned short PortNo,const char* IP)
|
|
{
|
|
SOCKADDR_IN remote;
|
|
memset((char*)&remote,0,sizeof(SOCKADDR_IN));
|
|
remote.sin_family=AF_INET;
|
|
remote.sin_port=htons(PortNo);
|
|
remote.sin_addr.s_addr=inet_addr(IP);
|
|
sendto(m_SocketSend,buf,len,0,(SOCKADDR*)&remote,sizeof(SOCKADDR_IN));
|
|
}
|
|
void CUDP::UDPRecv(char buf[],int len,unsigned short PortNo,const char* IP)
|
|
{
|
|
SOCKADDR_IN localRaddr,remoteSaddr;
|
|
localRaddr.sin_family=AF_INET;
|
|
localRaddr.sin_addr.S_un.S_addr=htons(INADDR_ANY);
|
|
localRaddr.sin_port=htons(PortNo);
|
|
|
|
|
|
remoteSaddr.sin_family=AF_INET;
|
|
remoteSaddr.sin_addr.S_un.S_addr=inet_addr(IP);
|
|
remoteSaddr.sin_port=htons(PortNo);
|
|
|
|
int socklen=sizeof(SOCKADDR_IN);
|
|
bind(m_SocketRecv,(SOCKADDR FAR*)&localRaddr,sizeof(SOCKADDR_IN));
|
|
recvfrom(m_SocketRecv,buf,len,0,(SOCKADDR*)&remoteSaddr,&socklen);
|
|
}
|
|
void CUDP::UDPClose()
|
|
{
|
|
closesocket(m_SocketRecv);
|
|
closesocket(m_SocketSend);
|
|
WSACleanup();
|
|
} |