📄 socketcomm.cpp
字号:
///////////////////////////////////////////////////////////////////////////////
// File: SocketComm.cpp
// Version: 1.1
//
// Author: Ernest Laurentin
// E-mail: elaurentin@sympatico.ca
//
// 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.
//
// An email letting me know how you are using it would be nice as well.
//
// 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
///////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include <stdio.h>
#include <tchar.h>
#include <process.h>
#include <crtdbg.h>
#include "SocketComm.h"
const DWORD DEFAULT_TIMEOUT = 100L;
///////////////////////////////////////////////////////////////////////////////
// SockAddrIn Struct
///////////////////////////////////////////////////////////////////////////////
// Copy
SockAddrIn& SockAddrIn::Copy(const SockAddrIn& sin)
{
memcpy(&this->sockAddrIn, &sin.sockAddrIn, Size());
return *this;
}
///////////////////////////////////////////////////////////////////////////////
// IsEqual
bool SockAddrIn::IsEqual(const SockAddrIn& sin)
{
// Is it Equal? - ignore 'sin_zero'
return (memcmp(&this->sockAddrIn, &sin.sockAddrIn, Size()-sizeof(sockAddrIn.sin_zero)) == 0);
}
///////////////////////////////////////////////////////////////////////////////
// IsGreater
bool SockAddrIn::IsGreater(const SockAddrIn& sin)
{
// Is it Greater? - ignore 'sin_zero'
return (memcmp(&this->sockAddrIn, &sin.sockAddrIn, Size()-sizeof(sockAddrIn.sin_zero)) > 0);
}
///////////////////////////////////////////////////////////////////////////////
// IsLower
bool SockAddrIn::IsLower(const SockAddrIn& sin)
{
// Is it Lower? - ignore 'sin_zero'
return (memcmp(&this->sockAddrIn, &sin.sockAddrIn, Size()-sizeof(sockAddrIn.sin_zero)) < 0);
}
///////////////////////////////////////////////////////////////////////////////
// CreateFrom
bool SockAddrIn::CreateFrom(LPCTSTR sAddr, LPCTSTR sService)
{
sockAddrIn.sin_addr.s_addr = htonl( CSocketComm::GetIPAddress(sAddr) );
sockAddrIn.sin_port = htons( CSocketComm::GetPortNumber( sService ) );
sockAddrIn.sin_family = AF_INET;
return true;
}
///////////////////////////////////////////////////////////////////////////////
// Construct & Destruct
//构造函数
CSocketComm::CSocketComm() :
m_hComm(INVALID_HANDLE_VALUE), m_hMutex(NULL), m_bServer(false),
m_bBroadcast(false), m_hThread(NULL)
{
}
CSocketComm::~CSocketComm()
{
//停止通信
StopComm();
}
///////////////////////////////////////////////////////////////////////////////
// Members
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// IsOpen
bool CSocketComm::IsOpen() const
{
return ( INVALID_HANDLE_VALUE != m_hComm );
}
///////////////////////////////////////////////////////////////////////////////
//判断是否启动
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句柄
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
// 转化网络字节到主机字节
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
///////////////////////////////////////////////////////////////////////////////
//获取IP地址,如果失败,则返回一个主机名
ULONG CSocketComm::GetIPAddress( LPCTSTR strHostName )
{
LPHOSTENT lphostent;
ULONG uAddr = INADDR_NONE;
//AfxMessageBox(strHostName);
if ( NULL != strHostName )
{
#ifdef _UNICODE
char strHost[HOSTNAME_SIZE] = { 0 };
WideCharToMultiByte(CP_ACP, 0, strHostName, -1, strHost, sizeof(strHost), NULL, NULL );
#else
LPCTSTR strHost = strHostName;
#endif
// 转化成标准ip地址
//AfxMessageBox(strHost);
uAddr = inet_addr( strHostName );
if ( (INADDR_NONE == uAddr) && (strcmp( strHost, "255.255.255.255" )) )
{
// 获得机器名
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 };
// 获得机器名
if (SOCKET_ERROR != gethostname(strHost, sizeof(strHost)))
{
struct hostent* hp;
hp = gethostbyname(strHost);
if (hp != NULL) {
strcpy(strHost, hp->h_name);
}
// 检查缓冲区大小
if (strlen(strHost) > nSize)
{
SetLastError(ERROR_INSUFFICIENT_BUFFER);
return false;
}
// Unicode转化
#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
///////////////////////////////////////////////////////////////////////////////
//获取本地计算机的标准IP地址,如"127.0.0.0"
bool CSocketComm::GetLocalAddress(LPTSTR strAddress, UINT nSize)
{
// 获得计算机本地地址
if (strAddress != NULL && nSize > 0)
{
char strHost[HOSTNAME_SIZE] = { 0 };
// 获得机器名
if (SOCKET_ERROR != gethostname(strHost, sizeof(strHost)))
{
struct hostent* hp;
hp = gethostbyname(strHost);
if (hp != NULL && hp->h_addr_list[0] != NULL)
{
// 查看地址是否是4字节大小
if ( hp->h_length < 4)
return false;
// 转化地址到点
strHost[0] = 0;
// 创建地址字符创
sprintf(strHost, "%u.%u.%u.%u",
(UINT)(((PBYTE) hp->h_addr_list[0])[0]),
(UINT)(((PBYTE) hp->h_addr_list[0])[1]),
(UINT)(((PBYTE) hp->h_addr_list[0])[2]),
(UINT)(((PBYTE) hp->h_addr_list[0])[3]));
// 检查缓冲区是否足够
if (strlen(strHost) > nSize)
{
SetLastError(ERROR_INSUFFICIENT_BUFFER);
return false;
}
// Unicode转换
#ifdef _UNICODE
return (0 != MultiByteToWideChar(CP_ACP, 0, strHost, -1, strAddress,
nSize, NULL, NULL ));
#else
_tcscpy(strAddress, strHost);
return true;
#endif
}
}
}
else
SetLastError(ERROR_INVALID_PARAMETER);
return false;
}
///////////////////////////////////////////////////////////////////////////////
// WaitForConnection
///////////////////////////////////////////////////////////////////////////////
// DESCRIPTION:
// Wait for a network connection. Only for connection type of socket
// This function may fail, in this case it returns "INVALID_SOCKET"
// PARAMETERS:
// SOCKET sock: a socket capable of receiving new connection (TCP: SOCK_STREAM)
///////////////////////////////////////////////////////////////////////////////
//等待一个网络连接,如果返回INVALID_SOCKET,表示失败
SOCKET CSocketComm::WaitForConnection(SOCKET sock)
{
// 接收一个连接
return accept(sock, 0, 0);
}
///////////////////////////////////////////////////////////////////////////////
// ShutdownConnection
///////////////////////////////////////////////////////////////////////////////
// DESCRIPTION:
// Shutdown a connection and close socket. This will force all
// transmission/reception to fail.
// PARAMETERS:
// SOCKET sock: Socket to close
///////////////////////////////////////////////////////////////////////////////
//关闭一个连接并关闭一个socket,这将强迫所有的传输和接收失败
bool CSocketComm::ShutdownConnection(SOCKET sock)
{
//
shutdown(sock, SD_BOTH);
return ( 0 == closesocket( sock ));
}
///////////////////////////////////////////////////////////////////////////////
// GetSockName
///////////////////////////////////////////////////////////////////////////////
// DESCRIPTION:
// retrieves the local name for a socket
// PARAMETERS:
// SockAddrIn& saddr_in: object to store address
///////////////////////////////////////////////////////////////////////////////
//获得socket名称
bool CSocketComm::GetSockName(SockAddrIn& saddr_in)
{
if (IsOpen())
{
int namelen = saddr_in.Size();
return (SOCKET_ERROR != getsockname(GetSocket(), (LPSOCKADDR)saddr_in, &namelen));
}
return false;
}
///////////////////////////////////////////////////////////////////////////////
// GetPeerName
///////////////////////////////////////////////////////////////////////////////
// DESCRIPTION:
// retrieves the name of the peer to which a socket is connected
// PARAMETERS:
// SockAddrIn& saddr_in: object to store address
///////////////////////////////////////////////////////////////////////////////
//获得socket要连接的地址
bool CSocketComm::GetPeerName(SockAddrIn& saddr_in)
{
if (IsOpen())
{
int namelen = saddr_in.Size();
return (SOCKET_ERROR != getpeername(GetSocket(), (LPSOCKADDR)saddr_in, &namelen));
}
return false;
}
///////////////////////////////////////////////////////////////////////////////
// CreateSocket
///////////////////////////////////////////////////////////////////////////////
// DESCRIPTION:
// This function creates a new socket for connection (SOCK_STREAM)
// or an connectionless socket (SOCK_DGRAM). A connectionless
// socket should not call "accept()" since it cannot receive new
// connection. This is used as SERVER socket
// PARAMETERS:
// LPCTSTR strServiceName: Service name or port number
// int nProtocol: protocol to use (set to AF_INET)
// int nType: type of socket to create (SOCK_STREAM, SOCK_DGRAM)
// UINT uOptions: other options to use
///////////////////////////////////////////////////////////////////////////////
bool CSocketComm::CreateSocket(LPCTSTR strServiceName, int nProtocol, int nType, UINT uOptions /* = 0 */)
{
// 如果已经打开,则返回false
if ( IsOpen() )
return false;
SOCKADDR_IN sockAddr = { 0 };
//地址设定
SOCKET sock = socket(nProtocol, nType, 0);
if (INVALID_SOCKET != sock)
{
sockAddr.sin_port = htons( GetPortNumber( strServiceName ) );
if ( 0 != sockAddr.sin_port)
{
sockAddr.sin_addr.s_addr = htonl( INADDR_ANY );
sockAddr.sin_family = nProtocol;
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -