首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网络技术 > 网络协议 >

socket: 无论IP是多少connect()函数总返回0解决方案

2012-02-04 
socket: 无论IP是多少connect()函数总返回0我想通过connect()函数访问一台网络设备,可是无论IP错误与否,co

socket: 无论IP是多少connect()函数总返回0
我想通过connect()函数访问一台网络设备,可是无论IP错误与否,connect总是返回0,只有在recv时接收数据超时才知道连接原来是失败的。阻塞模式和非阻塞模式我都试过了,实在不知道到底是什么原因。请高手帮忙,不甚感激!我将部分代码贴出来
WORD wVersionRequested;
WSADATA wsaData;
int err;
  struct hostent *pHostEntry;

  wVersionRequested = MAKEWORD( 2, 2 );
//加载套接字DLL库
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
return -1;
}

  // map host to ip, allow ip 
  if ((pHostEntry = gethostbyname(hostip))) {
memcpy((char *)&addr.sin_addr, pHostEntry->h_addr,
pHostEntry->h_length);
  }
  else if ((addr.sin_addr.s_addr = inet_addr(hostip))==INADDR_NONE) {
DBG_LOG (("Can't resolve %s\n", hostip));
return -1;
  }
  // create an IP network socket 
  sock = socket (AF_INET, SOCK_STREAM, 0);
{
// set a read timeout 
optval = READ_TIMEOUT*1000; // timeout in milliseconds 
if(setsockopt (sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&optval, 
sizeof (optval))==SOCKET_ERROR)
{closesocket (sock);
return -1;
  }

int bfsize;
int optsize = sizeof(bfsize);
if (getsockopt (sock, SOL_SOCKET, SO_RCVBUF,
(char *)&bfsize, &optsize) != SOCKET_ERROR) {
DBG_LOG (("rcvbuf is %u\n", bfsize));
}
bfsize = SOCK_BF_LEN;
if (setsockopt (sock, SOL_SOCKET, SO_RCVBUF,
(char *)&bfsize, sizeof(bfsize)) == SOCKET_ERROR) {
DBG_LOG (("failed to set rcvbuf to %u\n", bfsize));
}
else {
DBG_LOG (("rcvbuf set to %u\n", bfsize));
}
  }

  addr.sin_family = AF_INET;
  addr.sin_port = htons (80);

if (connect (sock, (struct sockaddr *)&addr, sizeof (addr)) == -1) {
DBG_LOG (("unable to connect\n"));
closesocket (sock);
}

[解决办法]
ddddddddddddddddddddddd

热点排行