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;
}

不知道什么原因,发送端口一直绑定失败,监视端口则可以绑定成功!!!!!!!

brayden
brayden
6577
编辑于2013-08-09
评论 (1)链接2013-08-09 
  • 0 支持
    我去!!两三天都没整明白!!求真大神现身!!! – 喷嘴杉杉 2013-08-11

windows下的我不熟悉,如果跟linux下的概念没啥差别的话,bind应该是绑定本地的出口地址,看的你的变量命名,似乎是想绑定接收端的地址。窃以为,你想做的应该是connect而不是bind

该答案已被锁定,无法对其进行评论,编辑及投票。
()
评论 (0)链接 • 2013-08-13

找到原因了,原来是端口复用的原因。将套接字设置成SO_REUSEADDR属性就好了。

但是现在出现了一个新的问题,之前我并没有设置成SO_REUSEADDR属性,但是一样可以正常运行!

该答案已被锁定,无法对其进行评论,编辑及投票。
()
评论 (0)链接 • 2013-08-15
德问是一个专业的编程问答社区,请 登录注册 后再提交答案