📄 socketcomm.cpp
字号:
///////////////////////////////////////////////////////////////////////////////
// File: SocketComm.cpp
// Version: 1.3
//
// Author: Ernest Laurentin
// E-mail: elaurentin@netzero.net
//
// Implementation of the CSocketComm and associated classes.
//
// This code may be used in compiled form in any way you desire. This
// file may be redistributed unmodified by any means PROVIDING it is
// not sold for profit without the authors written consent, and
// providing that this notice and the authors name and all copyright
// notices remains intact.
//
// This file is provided "as is" with no expressed or implied warranty.
// The author accepts no liability for any damage/loss of business that
// this c++ class may cause.
//
// Version history
//
// 1.0 - Initial release.
// 1.1 - Add support for Smart Addressing mode
// 1.2 - Fix various issues with address list (in UDP mode)
// 1.3 - Fix bug when sending message to broadcast address
///////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include <stdio.h>
#include <tchar.h>
#include <process.h>
#include <crtdbg.h>
#include "SocketComm.h"
const DWORD DEFAULT_TIMEOUT = 100L;
struct stMessageProxy
{
SockAddrIn address;
BYTE data[BUFFER_SIZE];
};
///////////////////////////////////////////////////////////////////////////////
// SockAddrIn Struct
///////////////////////////////////////////////////////////////////////////////
// Copy
SockAddrIn& SockAddrIn::Copy(const SockAddrIn& sin)
{
memcpy(this, &sin, Size());
return *this;
}
///////////////////////////////////////////////////////////////////////////////
// IsEqual
bool SockAddrIn::IsEqual(const SockAddrIn& sin)
{
// Is it Equal? - ignore 'sin_zero'
return (memcmp(this, &sin, Size()-sizeof(sin_zero)) == 0);
}
///////////////////////////////////////////////////////////////////////////////
// IsGreater
bool SockAddrIn::IsGreater(const SockAddrIn& sin)
{
// Is it Greater? - ignore 'sin_zero'
return (memcmp(this, &sin, Size()-sizeof(sin_zero)) > 0);
}
///////////////////////////////////////////////////////////////////////////////
// IsLower
bool SockAddrIn::IsLower(const SockAddrIn& sin)
{
// Is it Lower? - ignore 'sin_zero'
return (memcmp(this, &sin, Size()-sizeof(sin_zero)) < 0);
}
///////////////////////////////////////////////////////////////////////////////
// CreateFrom
bool SockAddrIn::CreateFrom(LPCTSTR sAddr, LPCTSTR sService, int nFamily /*=AF_INET*/)
{
Clear();
sin_addr.s_addr = htonl( CSocketComm::GetIPAddress(sAddr) );
sin_port = htons( CSocketComm::GetPortNumber( sService ) );
sin_family = nFamily;
return !IsNull();
}
///////////////////////////////////////////////////////////////////////////////
// Construct & Destruct
CSocketComm::CSocketComm() :
m_bServer(false), m_bSmartAddressing(false), m_bBroadcast(false),
m_hComm(INVALID_HANDLE_VALUE), m_hThread(NULL), m_hMutex(NULL)
{
}
CSocketComm::~CSocketComm()
{
StopComm();
}
///////////////////////////////////////////////////////////////////////////////
// Members
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// IsOpen
bool CSocketComm::IsOpen() const
{
return ( INVALID_HANDLE_VALUE != m_hComm );
}
///////////////////////////////////////////////////////////////////////////////
// IsStart
bool CSocketComm::IsStart() const
{
return ( NULL != m_hThread );
}
///////////////////////////////////////////////////////////////////////////////
// IsServer
bool CSocketComm::IsServer() const
{
return m_bServer;
}
///////////////////////////////////////////////////////////////////////////////
// IsBroadcast
bool CSocketComm::IsBroadcast() const
{
return m_bBroadcast;
}
///////////////////////////////////////////////////////////////////////////////
// IsSmartAddressing
bool CSocketComm::IsSmartAddressing() const
{
return m_bSmartAddressing;
}
///////////////////////////////////////////////////////////////////////////////
// GetSocket
SOCKET CSocketComm::GetSocket() const
{
return (SOCKET) m_hComm;
}
///////////////////////////////////////////////////////////////////////////////
// LockList
void CSocketComm::LockList()
{
if (NULL != m_hMutex)
WaitForSingleObject(m_hMutex, INFINITE);
}
///////////////////////////////////////////////////////////////////////////////
// UnlockList
void CSocketComm::UnlockList()
{
if (NULL != m_hMutex)
ReleaseMutex(m_hMutex);
}
///////////////////////////////////////////////////////////////////////////////
// AddToList
void CSocketComm::AddToList(const SockAddrIn& saddr_in)
{
LockList();
m_AddrList.insert( m_AddrList.end(), saddr_in );
UnlockList();
}
///////////////////////////////////////////////////////////////////////////////
// RemoveFromList
void CSocketComm::RemoveFromList(const SockAddrIn& saddr_in)
{
LockList();
m_AddrList.remove( saddr_in );
UnlockList();
}
///////////////////////////////////////////////////////////////////////////////
// SetServerState
void CSocketComm::SetServerState(bool bServer)
{
if (!IsStart())
m_bServer = bServer;
}
///////////////////////////////////////////////////////////////////////////////
// SetSmartAddressing : Address is included with message
void CSocketComm::SetSmartAddressing(bool bSmartAddressing)
{
if (!IsStart())
m_bSmartAddressing = bSmartAddressing;
}
///////////////////////////////////////////////////////////////////////////////
// OnDataReceived
///////////////////////////////////////////////////////////////////////////////
// DESCRIPTION:
// This function is PURE Virtual, you MUST overwrite it. This is
// called every time new data is available.
// PARAMETERS:
///////////////////////////////////////////////////////////////////////////////
void CSocketComm::OnDataReceived(const LPBYTE lpBuffer, DWORD dwCount)
{
}
///////////////////////////////////////////////////////////////////////////////
// OnEvent
///////////////////////////////////////////////////////////////////////////////
// DESCRIPTION:
// This function reports events & errors
// PARAMETERS:
// UINT uEvent: can be one of the event value EVT_(events)
///////////////////////////////////////////////////////////////////////////////
void CSocketComm::OnEvent(UINT uEvent)
{
}
///////////////////////////////////////////////////////////////////////////////
// GetPortNumber
///////////////////////////////////////////////////////////////////////////////
// DESCRIPTION:
// Returns a port number based on service name or port number string
// PARAMETERS:
// LPCTSTR strServiceName: Service name or port string
///////////////////////////////////////////////////////////////////////////////
USHORT CSocketComm::GetPortNumber( LPCTSTR strServiceName )
{
LPSERVENT lpservent;
USHORT nPortNumber = 0;
if ( _istdigit( strServiceName[0] ) ) {
nPortNumber = (USHORT) _ttoi( strServiceName );
}
else {
#ifdef _UNICODE
char pstrService[HOSTNAME_SIZE];
WideCharToMultiByte(CP_ACP, 0, pstrService, -1, strServiceName, sizeof(pstrService), NULL, NULL );
#else
LPCTSTR pstrDevice = strServiceName;
#endif
// Convert network byte order to host byte order
if ( (lpservent = getservbyname( pstrDevice, NULL )) != NULL )
nPortNumber = ntohs( lpservent->s_port );
}
return nPortNumber;
}
///////////////////////////////////////////////////////////////////////////////
// GetIPAddress
///////////////////////////////////////////////////////////////////////////////
// DESCRIPTION:
// Returns an IP address.
// - It tries to convert the string directly
// - If that fails, it tries to resolve it as a hostname
// PARAMETERS:
// LPCTSTR strHostName: host name to get IP address
///////////////////////////////////////////////////////////////////////////////
ULONG CSocketComm::GetIPAddress( LPCTSTR strHostName )
{
LPHOSTENT lphostent;
ULONG uAddr = INADDR_NONE;
TCHAR strLocal[HOSTNAME_SIZE] = { 0 };
// if no name specified, get local
if ( NULL == strHostName )
{
GetLocalName(strLocal, sizeof(strLocal));
strHostName = strLocal;
}
#ifdef _UNICODE
char strHost[HOSTNAME_SIZE] = { 0 };
WideCharToMultiByte(CP_ACP, 0, strHostName, -1, strHost, sizeof(strHost), NULL, NULL );
#else
LPCTSTR strHost = strHostName;
#endif
// Check for an Internet Protocol dotted address string
uAddr = inet_addr( strHost );
if ( (INADDR_NONE == uAddr) && (strcmp( strHost, "255.255.255.255" )) )
{
// It's not an address, then try to resolve it as a hostname
if ( lphostent = gethostbyname( strHost ) )
uAddr = *((ULONG *) lphostent->h_addr_list[0]);
}
return ntohl( uAddr );
}
///////////////////////////////////////////////////////////////////////////////
// GetLocalName
///////////////////////////////////////////////////////////////////////////////
// DESCRIPTION:
// Get local computer name. Something like: "mycomputer.myserver.net"
// PARAMETERS:
// LPTSTR strName: name of the computer is returned here
// UINT nSize: size max of buffer "strName"
///////////////////////////////////////////////////////////////////////////////
bool CSocketComm::GetLocalName(LPTSTR strName, UINT nSize)
{
if (strName != NULL && nSize > 0)
{
char strHost[HOSTNAME_SIZE] = { 0 };
// get host name, if fail, SetLastError is set
if (SOCKET_ERROR != gethostname(strHost, sizeof(strHost)))
{
struct hostent* hp;
hp = gethostbyname(strHost);
if (hp != NULL) {
strcpy(strHost, hp->h_name);
}
// check if user provide enough buffer
if (strlen(strHost) > nSize)
{
SetLastError(ERROR_INSUFFICIENT_BUFFER);
return false;
}
// Unicode conversion
#ifdef _UNICODE
return (0 != MultiByteToWideChar(CP_ACP, 0, strHost, -1, strName, nSize, NULL, NULL ));
#else
_tcscpy(strName, strHost);
return true;
#endif
}
}
else
SetLastError(ERROR_INVALID_PARAMETER);
return false;
}
///////////////////////////////////////////////////////////////////////////////
// GetLocalAddress
///////////////////////////////////////////////////////////////////////////////
// DESCRIPTION:
// Get TCP address of local computer in dot format ex: "127.0.0.0"
// PARAMETERS:
// LPTSTR strAddress: pointer to hold address string, must be long enough
// UINT nSize: maximum size of this buffer
///////////////////////////////////////////////////////////////////////////////
bool CSocketComm::GetLocalAddress(LPTSTR strAddress, UINT nSize)
{
// Get computer local address
if (strAddress != NULL && nSize > 0)
{
char strHost[HOSTNAME_SIZE] = { 0 };
// get host name, if fail, SetLastError is called
if (SOCKET_ERROR != gethostname(strHost, sizeof(strHost)))
{
struct hostent* hp;
hp = gethostbyname(strHost);
if(hp != NULL)
{
// Address is four bytes (32-bit)
if ( hp->h_length < 4)
return false;
int nPos=0;
for(int i = 0; i < hp->h_length/sizeof(int); i++)
{
ASSERT(hp->h_addr_list[i]!=NULL);
// Convert address to . format
strHost[nPos] = 0;
// Create Address string
sprintf(&strHost[nPos], "%u.%u.%u.%u ",
(UINT)(((PBYTE) hp->h_addr_list[i])[0]),
(UINT)(((PBYTE) hp->h_addr_list[i])[1]),
(UINT)(((PBYTE) hp->h_addr_list[i])[2]),
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -