下面是用c++builder写的,你参考一下。
int ConnSock(const char *HostIp,const unsigned long Port,const long TimeOutUSec)
{
extern int errno;
struct hostent *phe; /* pointer to host information entry */
struct servent *pse; /* pointer to service information entry */
struct protoent *ppe; /* pointer to protocol information entry */
struct sockaddr_in sin; /* an Internet endpoint address */
//unsigned
int SockFd, type = SOCK_STREAM; /* socket descriptor and socket type */
int flags,n,error;
int len;
int ret,rc;
struct fd_set afds;
struct fd_set wfds;
struct timeval tval;
unsigned long blkstate = 0;
memset((char *)&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
/* Map service name to port number */
if ((sin.sin_port = htons((u_short)Port)) == 0)
{
return(-1);
}
/* Map host name to IP address, allowing for dotted decimal */
if(HostIp!=NULL)
{
if ((phe = gethostbyname(HostIp)) != NULL)
{
memcpy((char *)&sin.sin_addr, phe->h_addr, phe->h_length);
}
else if ((sin.sin_addr.s_addr = inet_addr(HostIp)) == INADDR_NONE)
{
return(-2);
}
}
else
{
sin.sin_addr.s_addr = inet_addr(HostIp);
}
/* Map protocol name to protocol number */
if ((ppe = getprotobyname("tcp")) == 0)
{
return(-3);
}
SockFd = socket(PF_INET, type, ppe->p_proto);
if (SockFd == INVALID_SOCKET)
{
return (-4);
}
if(ioctlsocket(SockFd,FIONBIO,&blkstate) != 0)
{
CloseSocket(SockFd);
return (-5);
}
/* Connect the socket */
if (connect(SockFd, (struct sockaddr *)&sin, sizeof(sin)) == SOCKET_ERROR)
{
if (WSAGetLastError() != WSAEWOULDBLOCK)
{
CloseSocket(SockFd);
return(-6);
}
}
FD_ZERO(&afds);
FD_SET((unsigned long)SockFd,&afds);
wfds=afds;
tval.tv_sec= TimeOutUSec / 1000;
tval.tv_usec=TimeOutUSec % 1000;
//blkstate = 0;
if(ioctlsocket (SockFd,FIONBIO,&blkstate) != 0)
{
CloseSocket(SockFd);
return (-7);
}
if (select(SockFd+1,&afds,&wfds,NULL,&tval) == 0)
{
CloseSocket(SockFd);
return(-8);
}
if (! FD_ISSET(SockFd,&wfds))
{
/* select error: sockfd not set */
CloseSocket(SockFd);
return(-9);
}
/* restore file status flags */
if(ioctlsocket (SockFd,FIONBIO,&blkstate) != 0)
{
CloseSocket(SockFd);
return (-10);
}
return(SockFd);
}/* End: ConnSock */