2008년 08월 01일
Network Programming Tip #1 - timeout, resolv
// select를 이용한 타임아웃 설정.
int timeout(int sock, int secs) {
struct timeval tout;
fd_set fd_read;
tout.tv_sec = secs;
tout.tv_usec = 0;
FD_ZERO(&fd_read);
FD_SET(sock, &fd_read);
if(select(sock + 1, &fd_read, NULL, NULL, &tout)
<= 0) return(-1);
return(0);
}
// WSASocket 기반으로 작성할 경우 WSAOVERLAPPED를 이용하여 이벤트 기반으로 Timeout을 설정할 수 있다.
// 아래는 설정의 한 예
int ret=WSARecv(Sock,&RecvBuf,1,&nRead,&Flag,&RecvOverlapped,NULL);
if(ret==SOCKET_ERROR && (WSA_IO_PENDING!=WSAGetLastError()))
{
cout<<"Error when receiving"<<endl;
return SOCKET_ERROR;
}
ret=WSAWaitForMultipleEvents(1,&RecvOverlapped.hEvent,TRUE,timeOut,TRUE);
if(WAIT_FAILED==ret)
{
cout<<"wait failed"<<endl;
return SOCKET_ERROR;
}
// 호스트이름에 대한 resolve가 필요할 때 아래 함수를 쓰면 끝.
u32 resolv(char *host) {
struct hostent *hp;
u32 host_ip;
host_ip = inet_addr(host);
if(host_ip == INADDR_NONE) {
hp = gethostbyname(host);
if(!hp) {
printf("\nError: Unable to resolv hostname (%s)\n", host);
exit(1);
} else host_ip = *(u32 *)hp->h_addr;
}
return(host_ip);
}
// 혹시 이 포스트를 보시면서 좀 더 나은 형태의 TIMEOUT 방법을 아시는 분은 공유좀... ^^;;
# by | 2008/08/01 11:55 | Programming | 트랙백 | 덧글(2)




