📄 ysocket.h
字号:
{
struct sockaddr_in SockAddr;
SockAddr.sin_family=AF_INET;
SockAddr.sin_port=nHostPort;
SockAddr.sin_addr.s_addr =inet_addr(lpszHostAddress) ;
return SendTo(lpBuf,nBufLen,(sockaddr *)&SockAddr,nSecs);
}
template <class STRING>
int YSocket<STRING>::SendTo(const void* lpBuf, int nBufLen,
const SOCKADDR* lpSockAddr, const int nSecs)
{
int ret,nBytesReceived=0;
ret=JugeTime(0,2);
if(ret==2){//可以写
if((nBytesReceived=sendto(m_hSocket,(char*)lpBuf,nBufLen,0,lpSockAddr,sizeof(lpSockAddr)))==SOCKET_ERROR){
STRING tp;tp.Format("Send.no.1:%s",GetErrorStr());
throw tp ;
}
}else return 0;
return nBytesReceived;
}
template <class STRING>
int YSocket<STRING>::SendTo(const void* lpBuf, int nBufLen,
const int nSecs)
{
SOCKADDR* lpSockAddr=&tpserver;
int ret,nBytesReceived=0;
ret=JugeTime();
if(ret==2){//可以写
if((nBytesReceived=sendto(m_hSocket,(char*)lpBuf,nBufLen,0,lpSockAddr,sizeof(lpSockAddr)))==SOCKET_ERROR){
STRING tp;tp.Format("Send.no.2:%s",GetErrorStr());
throw tp ;
}
}else return 0;
return nBytesReceived;
}
//得到cmysock中ip的端口字符串
template <class STRING>
STRING YSocket<STRING>::GetPort(YSocket& pSock)
{
STRING s_rt;
s_rt.Format("%d",ntohs(((sockaddr_in*)&(this->tpserver))->sin_port));//得到端口号
return s_rt;
}
template <class STRING>
STRING YSocket<STRING>::GetErrorStr()
{
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL
);
STRING s_rt;
s_rt = (LPCTSTR)lpMsgBuf;
return s_rt;
switch(WSAGetLastError()){
case WSAEACCES ://(10013)
s_rt = "Permission denied. \nAn attempt was made to access a socket in a way forbidden by its access permissions. An example is using a broadcast address for sendto without broadcast permission being set using setsockopt(SO_BROADCAST). ";
break;
case WSAEADDRINUSE ://(10048)
s_rt = "Address already in use. \nOnly one usage of each socket address (protocol/IP address/port) is normally permitted. This error occurs if an application attempts to bind a socket to an IP address/port that has already been used for an existing socket, or a socket that wasn't closed properly, or one that is still in the process of closing. For server applications that need to bind multiple sockets to the same port number, consider using setsockopt(SO_REUSEADDR). Client applications usually need not call bind at all - connect will choose an unused port automatically. When bind is called with a wild-card address (involving ADDR_ANY), a WSAEADDRINUSE error could be delayed until the specific address is \"committed.\" This could happen with a call to other function later, including connect, listen, WSAConnect or WSAJoinLeaf. ";
break;
case WSAEADDRNOTAVAIL ://(10049)
s_rt = "Cannot assign requested address. \nThe requested address is not valid in its context. Normally results from an attempt to bind to an address that is not valid for the local machine. This can also result from connect, sendto, WSAConnect, WSAJoinLeaf, or WSASendTo when the remote address or port is not valid for a remote machine (e.g. address or port 0). ";
break;
case WSAEAFNOSUPPORT ://(10047)
s_rt = "Address family not supported by protocol family. \nAn address incompatible with the requested protocol was used. All sockets are created with an associated \"address family\" (i.e. AF_INET for Internet Protocols) and a generic protocol type (i.e. SOCK_STREAM). This error will be returned if an incorrect protocol is explicitly requested in the socket call, or if an address of the wrong family is used for a socket, e.g. in sendto. ";
break;
case WSAEALREADY ://(10037)
s_rt = "Operation already in progress. \nAn operation was attempted on a non-blocking socket that already had an operation in progress - i.e. calling connect a second time on a non-blocking socket that is already connecting, or canceling an asynchronous request (WSAAsyncGetXbyY) that has already been canceled or completed. ";
break;
case WSAECONNABORTED ://(10053)
s_rt = "Software caused connection abort. \nAn established connection was aborted by the software in your host machine, possibly due to a data transmission timeout or protocol error. ";
break;
case WSAECONNREFUSED ://(10061)
s_rt = "Connection refused. \nNo connection could be made because the target machine actively refused it. This usually results from trying to connect to a service that is inactive on the foreign host - i.e. one with no server application running. ";
break;
case WSAECONNRESET ://(10054)
s_rt = "Connection reset by peer. \nA existing connection was forcibly closed by the remote host. This normally results if the peer application on the remote host is suddenly stopped, the host is rebooted, or the remote host used a \"hard close\" (see setsockopt for more information on the SO_LINGER option on the remote socket.) This error may also result if a connection was broken due to \"keep-alive\" activity detecting a failure while one or more operations are in progress. Operations that were in progress fail with WSAENETRESET. Subsequent operations fail with WSAECONNRESET. "; break;
case WSAEDESTADDRREQ ://(10039)
s_rt = "Destination address required. \nA required address was omitted from an operation on a socket. For example, this error will be returned if sendto is called with the remote address of ADDR_ANY. "; break;
case WSAEFAULT ://(10014)
s_rt = "Bad address. \nThe system detected an invalid pointer address in attempting to use a pointer argument of a call. This error occurs if an application passes an invalid pointer value, or if the length of the buffer is too small. For instance, if the length of an argument which is a struct sockaddr is smaller than sizeof(struct sockaddr). "; break;
case WSAEHOSTDOWN ://(10064)
s_rt = "Host is down. \nA socket operation failed because the destination host was down. A socket operation encountered a dead host. Networking activity on the local host has not been initiated. These conditions are more likely to be indicated by the error WSAETIMEDOUT. "; break;
case WSAEHOSTUNREACH ://(10065)
s_rt = "No route to host. \nA socket operation was attempted to an unreachable host. See WSAENETUNREACH "; break;
case WSAEINPROGRESS ://(10036)
s_rt = "Operation now in progress. \nA blocking operation is currently executing. Windows Sockets only allows a single blocking operation to be outstanding per task (or thread), and if any other function call is made (whether or not it references that or any other socket) the function fails with the WSAEINPROGRESS error. "; break;
case WSAEINTR ://(10004)
s_rt = "Interrupted function call. \nA blocking operation was interrupted by a call to WSACancelBlockingCall. "; break;
case WSAEINVAL ://(10022)
s_rt = "Invalid argument. \nSome invalid argument was supplied (for example, specifying an invalid level to the setsockopt function). In some instances, it also refers to the current state of the socket - for instance, calling accept on a socket that is not listening. "; break;
case WSAEISCONN ://(10056)
s_rt = "Socket is already connected. \nA connect request was made on an already connected socket. Some implementations also return this error if sendto is called on a connected SOCK_DGRAM socket (For SOCK_STREAM sockets, the to parameter in sendto is ignored), although other implementations treat this as a legal occurrence. "; break;
case WSAEMFILE ://(10024)
s_rt = "Too many open files. \nToo many open sockets. Each implementation may have a maximum number of socket handles available, either globally, per process or per thread. "; break;
case WSAEMSGSIZE ://(10040)
s_rt = "Message too long. \nA message sent on a datagram socket was larger than the internal message buffer or some other network limit, or the buffer used to receive a datagram into was smaller than the datagram itself. "; break;
case WSAENETDOWN ://(10050)
s_rt = "Network is down. \nA socket operation encountered a dead network. This could indicate a serious failure of the network system (i.e. the protocol stack that the WinSock DLL runs over), the network interface, or the local network itself. "; break;
case WSAENETRESET ://(10052)
s_rt = "Network dropped connection on reset. \nThe connection has been broken due to \"keep-alive\" activity detecting a failure while the operation was in progress. It can also be returned by setsockopt if an attempt is made to set SO_KEEPALIVE on a connection that has already failed. "; break;
case WSAENETUNREACH ://(10051)
s_rt = "Network is unreachable. \nA socket operation was attempted to an unreachable network. This usually means the local software knows no route to reach the remote host. "; break;
case WSAENOBUFS ://(10055)
s_rt = "No buffer space available. \nAn operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full. "; break;
case WSAENOPROTOOPT://(10042)
s_rt = "Bad protocol option. \nAn unknown, invalid or unsupported option or level was specified in a getsockopt or setsockopt call. "; break;
case WSAENOTCONN ://(10057)
s_rt = "Socket is not connected. \nA request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using sendto) no address was supplied. Any other type of operation might also return this error - for example, setsockopt setting SO_KEEPALIVE if the connection has been reset. "; break;
case WSAENOTSOCK ://(10038)
s_rt = "Socket operation on non-socket. \nAn operation was attempted on something that is not a socket. Either the socket handle parameter did not reference a valid socket, or for select, a member of an fd_set was not valid. "; break;
case WSAEOPNOTSUPP ://(10045)
s_rt = "Operation not supported. \nThe attempted operation is not supported for the type of object referenced. Usually this occurs when a socket descriptor to a socket that cannot support this operation, for example, trying to accept a connection on a datagram socket. "; break;
case WSAEPFNOSUPPORT ://(10046)
s_rt = "Protocol family not supported. \nThe protocol family has not been configured into the system or no implementation for it exists. Has a slightly different meaning to WSAEAFNOSUPPORT, but is interchangeable in most cases, and all Windows Sockets functions that return one of these specify WSAEAFNOSUPPORT. "; break;
case WSAEPROCLIM ://(10067)
s_rt = "Too many processes. \nA Windows Sockets implementation may have a limit on the number of applications that may use it simultaneously. WSAStartup may fail with this error if the limit has been reached. "; break;
case WSAEPROTONOSUPPORT ://(10043)
s_rt = "Protocol not supported. \nThe requested protocol has not been configured into the system, or no implementation for it exists. For example, a socket call requests a SOCK_DGRAM socket, but specifies a stream protocol. "; break;
case WSAEPROTOTYPE ://(10041)
s_rt = "Protocol wrong type for socket. \nA protocol was specified in the socket function call that does not support the semantics of the socket type requested. For example, the ARPA Internet UDP protocol cannot be specified with a socket type of SOCK_STREAM. "; break;
case WSAESHUTDOWN ://(10058)
s_rt = "Cannot send after socket shutdown. \nA request to send or receive data was disallowed because the socket had already been shut down in that direction with a previous shutdown call. By calling shutdown a partial close of a socket is requested, which is a signal that sending or receiving or both has been discontinued. "; break;
case WSAESOCKTNOSUPPORT ://(10044)
s_rt = "Socket type not supported. \nThe support for the specified socket type does not exist in this address family. For example, the optional type SOCK_RAW might be selected in a socket call, and the implementation does not support SOCK_RAW sockets at all. "; break;
case WSAETIMEDOUT ://(10060)
s_rt = "Connection timed out. \nA connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. ";
break;
case WSATYPE_NOT_FOUND ://(10109)
s_rt = "Class type not found. \nThe specified class was not found. ";
break;
case WSAEWOULDBLOCK ://(10035)
s_rt = "Resource temporarily unavailable. \nThis error is returned from operations on non-blocking sockets that cannot be completed immediately, for example recv when no data is queued to be read from the socket. It is a non-fatal error, and the operation should be retried later. It is normal for WSAEWOULDBLOCK to be reported as the result from calling connect on a non-blocking SOCK_STREAM socket, since some time must elapse for the connection to be established. ";
break;
case WSAHOST_NOT_FOUND ://(11001)
s_rt = "Host not found. \nNo such host is known. The name is not an official hostname or alias, or it cannot be found in the database(s) being queried. This error may also be returned for protocol and service queries, and means the specified name could not be found in the relevant database. ";
break;
case WSA_INVALID_HANDLE ://(OS dependent)
s_rt = "Specified event object handle is invalid. \nAn application attempts to use an event object, but the specified handle is not valid. ";
break;
case WSA_INVALID_PARAMETER ://(OS dependent)
s_rt = "One or more parameters are invalid. \nAn application used a Windows Sockets function which directly maps to a Win32 function. The Win32 function is indicating a problem with one or more parameters. ";
//case WSAINVALIDPROCTABLE ://(OS dependent)
// s_rt = "Invalid procedure table from service provider. \nA service provider returned a bogus proc table to WS2_32.DLL. (Usually caused by one or more of the function pointers being NULL.) ";
//case WSAINVALIDPROVIDER ://(OS dependent)
// s_rt = "Invalid service provider version number. \nA service provider returned a version number other than 2.0. ";
break;
case WSA_IO_INCOMPLETE ://(OS dependent)
s_rt = "Overlapped I/O event object not in signaled state. \nThe application has tried to determine the status of an overlapped operation which is not yet completed. Applications that use WSAGetOverlappedResult (with the fWait flag set to false) in a polling mode to determine when an overlapped operation has completed will get this error code until the operation is complete. ";
break;
case WSA_IO_PENDING ://(OS dependent)
s_rt = "Overlapped operations will complete later. \nThe application has initiated an overlapped operation which cannot be completed immediately. A completion indication will be given at a later time when the operation has been completed. ";
break;
case WSA_NOT_ENOUGH_MEMORY ://(OS dependent)
s_rt = "Insufficient memory available. \nAn application used a Windows Sockets function which directly maps to a Win32 function. The Win32 function is indicating a lack of required memory resources. ";
break;
case WSANOTINITIALISED ://(10093)
s_rt = "Successful WSAStartup not yet performed. \nEither the application hasn't called WSAStartup or WSAStartup failed. The application may be accessing a socket which the current active task does not own (i.e. trying to share a socket between tasks), or WSACleanup has been called too many times. ";
break;
case WSANO_DATA ://(11004)
s_rt = "Valid name, no data record of requested type. \nThe requested name is valid and was found in the database, but it does not have the correct associated data being resolved for. The usual example for this is a hostname -> address translation attempt (using gethostbyname or WSAAsyncGetHostByName) which uses the DNS (Domain Name Server), and an MX record is returned but no A record - indicating the host itself exists, but is not directly reachable. ";
break;
case WSANO_RECOVERY://(11003)
s_rt = "This is a non-recoverable error. \nThis indicates some sort of non-recoverable error occurred during a database lookup. This may be because the database files (e.g. BSD-compatible HOSTS, SERVICES or PROTOCOLS files) could not be found, or a DNS request was returned by the server with a severe error. ";
//case WSAPROVIDERFAILEDINIT ://(OS dependent)
// s_rt = "Unable to initialize a service provider. \nEither a service provider's DLL could not be loaded (LoadLibrary failed) or the provider's WSPStartup/NSPStartup function failed. ";
break;
case WSASYSCALLFAILURE ://(OS dependent)
s_rt = "System call failure. \nReturned when a system call that should never fail does. For example, if a call to WaitForMultipleObjects fails or one of the registry functions fails trying to manipulate theprotocol/namespace catalogs. ";
break;
case WSASYSNOTREADY ://(10091)
s_rt = "Network subsystem is unavailable. \nThis error is returned by WSAStartup if the Windows Sockets implementation cannot function at this time because the underlying system it uses to provide network services is currently unavailable. Users should check: \nthat the appropria Windows Sockets DLL file is in the current path, \nthat they are not trying to use more than one Windows Sockets implementation simultaneously. If there is more than one WINSOCK DLL on your system, be sure the first one in the path is appropriate for the network subsystem currently loaded. \nthe Windows Sockets implementation documentation to be sure all necessary components are currently installed and configured correctly. ";
break;
case WSATRY_AGAIN ://(11002)
s_rt = "Non-authoritative host not found. \nThis is usually a temporary error during hostname resolution and means that the local server did not receive a response from an authoritative server. A retry at some time later may be successful. ";
break;
case WSAVERNOTSUPPORTED ://(10092)
s_rt = "WINSOCK.DLL version out of range. \nThe current Windows Sockets implementation does not support the Windows Sockets specification version requested by the application. Check that no old Windows Sockets DLL files are being accessed. ";
break;
case WSAEDISCON ://(10094)
s_rt = "Graceful shutdown in progress. \nReturned by WSARecv and WSARecvFrom to indicate the remote party has initiated a graceful shutdown sequence. ";
break; break;
case WSA_OPERATION_ABORTED ://(OS dependent)
s_rt = "Overlapped operation aborted. \nAn overlapped operation was canceled due to the closure of the socket, or the execution of the SIO_FLUSH command in WSAIoctl. ";
}
return s_rt;
}
template <class STRING>
STRING& YSocket<STRING>::GetPort()
{
if(!(sfGetP&2)){
PORT = ntohs(((sockaddr_in*)&(this->tpserver))->sin_port);
m_strPORT.Format("%d",PORT );//得到端口号
sfGetP |= 2;
}
return m_strPORT;
}
template <class STRING>
UINT YSocket<STRING>::GetLocPort(SOCKET s){
SOCKADDR local;int len=sizeof(local);
UINT port=0;
if(getsockname(s,&local,&len) == 0){
port = ntohs(((sockaddr_in*)&local)->sin_port);
}
return port ;
}
template <class STRING>
STRING YSocket<STRING>::GetLocPort(){
LocPORT = GetLocPort(m_hSocket);
m_strLocPORT.Format("%d",LocPORT );//得到端口号
return m_strLocPORT ;
}
//得到cmysock中ip的地址字符串
template <class STRING>
STRING YSocket<STRING>::GetIpAdd(YSocket& pSock)
{
return inet_ntoa(((sockaddr_in*)&(pSock.tpserver))->sin_addr);
}
template <class STRING>
STRING YSocket<STRING>::GetIpAdd(STRING tpdomain)
{
hostent* hp=NULL;
if((hp = gethostbyname(tpdomain)) != NULL){
SOCKADDR_IN server;
server.sin_family = AF_INET;
memcpy(&(server.sin_addr),hp->h_addr_list[0],hp->h_length);
//if(hp!=NULL)delete hp;
return inet_ntoa(((sockaddr_in*)&(server))->sin_addr);
}else{
return "";
}
}
template <class STRING>
STRING YSocket<STRING>::GetIpAdd(int mode)
{
if(!(sfGetP&1)||mode==1){
m_strIPADD = inet_ntoa(((sockaddr_in*)&(this->tpserver))->sin_addr);
sfGetP |= 1;
}
return m_strIPADD;
}
template <class STRING>
STRING YSocket<STRING>::GetLocIpAdd(SOCKET s){
SOCKADDR local;int len = sizeof(local);
if(getsockname(s,&local,&len) == 0){
return inet_ntoa(((sockaddr_in*)&local)->sin_addr);
}
return "" ;
}
template <class STRING>
STRING YSocket<STRING>::GetLocIpAdd(){
m_strLocIPADD = GetLocIpAdd(m_hSocket);
return m_strLocIPADD ;
}
template <class STRING>
YSocket<STRING>& YSocket<STRING>::operator=(YSocket& tp){
this->m_hSocket=tp.m_hSocket;
this->nSTP = tp.nSTP;
this->tpserver=tp.tpserver;
this->IsLive=tp.IsLive;
this->SEQ = tp.SEQ;
this->sfGetP = 0;
tp.IsLive=0;
this->GetIpAdd(1);
return *this;
}
template <class STRING>
YSocket<STRING>& YSocket<STRING>::operator=(YSocket* tp){
this->m_hSocket=tp->m_hSocket;
this->nSTP = tp->nSTP;
this->tpserver=tp->tpserver;
this->IsLive=tp->IsLive;
this->SEQ = tp->SEQ;
this->sfGetP = 0;
tp->IsLive=0;
this->GetIpAdd(1);
return *this;
}
#endif
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -