编译器:VS2008
偶将 UDP 封装成类,绑定的主机地址,作为类成员
class CUDPSocket
{
public:
CUDPSocket();
~CUDPSocket();
bool InitSocket();
int SendData(char *buffer,int len,sockaddr_in RecieverAddr);
int RecvData(char *buffer,int len,sockaddr_in &SenderAddr);
int RecvData_Select(char *buffer,int len,sockaddr_in &SenderAddr);
BOOL GetHostIP(char *IP);
private:
sockaddr_in HostAddr;
SOCKET ServerSocket;
};
可初始化InitSocket()时,bind端口函数老是出现WSAEFAULT 错误(socket地址赋值没任何问题),查阅MSDN:
A name consists of three parts when using the Internet address family: the address family, a host address, and a port number that identifies the application. In Windows Sockets 2, the name parameter is not strictly interpreted as a pointer to a SOCKADDR structure. It is cast this way for Windows Sockets 1.1 compatibility. Service Providers are free to regard it as a pointer to a block of memory of size namelen. The first two bytes in this block (corresponding to the sa_family member of the SOCKADDR structure) must contain the address family that was used to create the socket. Otherwise, an error WSAEFAULT will occur.
没太看明白,只说sockaddr_in.sa_family (The first two bytes),必须包含协议族。否则出现这个错误。
郁闷许久,后来,将sockaddr_in HostAddr;换成局部变量就OK了~~,谁能解释下,sockaddr_in HostAddr;作为成员变量时为啥不行。