VC-socket套接字,bind绑定发送端口失败!!求救!!
#include "winsock.h"
class CSocketOperator
{
public:
CSocketOperator();
virtual ~CSocketOperator();
BOOL InitLocal(CString localIP,const UINT localPort);
BOOL InitTarget(CString targetIP,const UINT targetPort);
BOOL CloseLocal();
BOOL CloseTarget();
BOOL CloseAllSocket();
BOOL IsTarget();
BOOL IsLocal();
void GetString(TCHAR *&b,int &ret,CString &ip,int &port);
void SendString(TCHAR *a,int len_a);
void ReSend();
TCHAR *GetCurrentSend();
private:
SOCKET m_localSock,m_targetSock;
sockaddr_in m_localAddr,m_targetAddr,m_sourceAddr,m_from;
int len_addr,m_nLen;
TCHAR getBuffer[65],*m_pcCurrentSend;
};
CSocketOperator::CSocketOperator()
{
WSADATA wsaData;
WORD version=MAKEWORD(2,0);
if(WSAStartup(version,&wsaData)!=0)
{
AfxMessageBox(_T("winsocket启动失败!"));
}
m_localSock=NULL;
m_targetSock=NULL;
len_addr=sizeof(sockaddr_in);
}
BOOL CSocketOperator::InitTarget(CString targetIP,const UINT targetPort)
{
if(m_targetSock!=NULL)
{
closesocket(m_targetSock);
m_targetSock=NULL;
}
m_targetSock=socket(AF_INET,SOCK_DGRAM,0);
//目标地址
m_targetAddr.sin_family=AF_INET;
m_targetAddr.sin_addr.S_un.S_addr=inet_addr(targetIP.GetBuffer(0));
m_targetAddr.sin_port=htons(targetPort);
for(int i=0;i<5;i++)
{
if(bind(m_targetSock,(PSOCKADDR)&m_sourceAddr,len_addr)!=SOCKET_ERROR)
return TRUE;
Sleep(100);
}
AfxMessageBox(_T("发送端口绑定失败!"));
closesocket(m_targetSock);
m_targetSock=NULL;
return FALSE;
}
BOOL CSocketOperator::InitLocal(CString localIP,const UINT localPort)
{
if(m_localSock!=NULL)
{
closesocket(m_localSock);
m_localSock=NULL;
}
m_localSock=socket(AF_INET,SOCK_DGRAM,0);
//本机地址
m_localAddr.sin_family=AF_INET;
m_localAddr.sin_addr.S_un.S_addr=inet_addr(localIP.GetBuffer(0));
m_localAddr.sin_port=htons(localPort);
//源地址
m_sourceAddr.sin_family=AF_INET;
m_sourceAddr.sin_addr.S_un.S_addr=inet_addr(localIP.GetBuffer(0));
m_sourceAddr.sin_port=htons(localPort);
//绑定套接字
for(int i=0;i<5;i++)
{
if(bind(m_localSock,(PSOCKADDR)&m_localAddr,len_addr)!=SOCKET_ERROR)
return TRUE;
Sleep(100);
}
AfxMessageBox(_T("监视端口绑定失败!"));
closesocket(m_localSock);
m_localSock=NULL;
return FALSE;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
windows下的我不熟悉,如果跟linux下的概念没啥差别的话,bind应该是绑定本地的出口地址,看的你的变量命名,似乎是想绑定接收端的地址。窃以为,你想做的应该是connect而不是bind
找到原因了,原来是端口复用的原因。将套接字设置成SO_REUSEADDR属性就好了。
但是现在出现了一个新的问题,之前我并没有设置成SO_REUSEADDR属性,但是一样可以正常运行!