当前位置: 技术问答>linux和unix
socket fd_isset返回总是0,什么原因啊??
来源: 互联网 发布时间:2016-03-29
本文导语: server端的代码如下,client端向server端发起connect请求,但server端FD_ISSET(sd, &fds)返回的总是0,应该是1 啊,是什么原因呢 (retval返回的是1)? int main() { int sd ; int cflag=1; int sm, new_fd; int i,rc; int fd_num=1; int maxf...
server端的代码如下,client端向server端发起connect请求,但server端FD_ISSET(sd, &fds)返回的总是0,应该是1 啊,是什么原因呢
(retval返回的是1)?
int main()
{
int sd ;
int cflag=1;
int sm, new_fd;
int i,rc;
int fd_num=1;
int maxfd;
int retval;
int sin_size;
char *cip;
char buf[100];
fd_set fds;
struct sockaddr_in sin;
if ((sd = socket( AF_INET, SOCK_STREAM, 0 )) == -1)
{
perror( "socket.c: Errer in socket()" );
return 0;
}
if(setsockopt(sd,SOL_SOCKET,SO_REUSEADDR,(char *)&cflag,sizeof(cflag))==-1)
{
printf("setsockopt() errorn");
exit(-1);
}
sin.sin_family=AF_INET;
sin.sin_port=htons(2345);
sin.sin_addr.s_addr=INADDR_ANY;
bzero(&(sin.sin_zero),8);
sin_size=sizeof(struct sockaddr_in);
if ((bind(sd, (struct sockaddr *)&sin,sizeof(sin)) == -1) ||
(listen(sd, 10 ) == -1))
{
perror( "socket.c: Error in bind() or listen()" );
return -1;
}
printf( "n========= success bind ========= n" );
FD_ZERO(&fds);
FD_SET(sd,&fds);
maxfd=sd;
while(1)
{
retval = select(maxfd+1, &fds, NULL, NULL, NULL);
printf("retval: %dn",retval);
if(retval)
{
printf("sd : %dn",sd);
printf("fd_isset sd val : %dn",FD_ISSET(sd, &fds));
if(FD_ISSET(sd, &fds))
{
printf("11111111111111n");
new_fd = accept(sd,(struct sockaddr *)&sin, &sin_size );
if( new_fd maxfd)?new_fd:maxfd;
FD_SET(new_fd, &fds);
fd_num++;
}
else {
printf("33333333333333333n");
return 0;}
}
}
}
(retval返回的是1)?
int main()
{
int sd ;
int cflag=1;
int sm, new_fd;
int i,rc;
int fd_num=1;
int maxfd;
int retval;
int sin_size;
char *cip;
char buf[100];
fd_set fds;
struct sockaddr_in sin;
if ((sd = socket( AF_INET, SOCK_STREAM, 0 )) == -1)
{
perror( "socket.c: Errer in socket()" );
return 0;
}
if(setsockopt(sd,SOL_SOCKET,SO_REUSEADDR,(char *)&cflag,sizeof(cflag))==-1)
{
printf("setsockopt() errorn");
exit(-1);
}
sin.sin_family=AF_INET;
sin.sin_port=htons(2345);
sin.sin_addr.s_addr=INADDR_ANY;
bzero(&(sin.sin_zero),8);
sin_size=sizeof(struct sockaddr_in);
if ((bind(sd, (struct sockaddr *)&sin,sizeof(sin)) == -1) ||
(listen(sd, 10 ) == -1))
{
perror( "socket.c: Error in bind() or listen()" );
return -1;
}
printf( "n========= success bind ========= n" );
FD_ZERO(&fds);
FD_SET(sd,&fds);
maxfd=sd;
while(1)
{
retval = select(maxfd+1, &fds, NULL, NULL, NULL);
printf("retval: %dn",retval);
if(retval)
{
printf("sd : %dn",sd);
printf("fd_isset sd val : %dn",FD_ISSET(sd, &fds));
if(FD_ISSET(sd, &fds))
{
printf("11111111111111n");
new_fd = accept(sd,(struct sockaddr *)&sin, &sin_size );
if( new_fd maxfd)?new_fd:maxfd;
FD_SET(new_fd, &fds);
fd_num++;
}
else {
printf("33333333333333333n");
return 0;}
}
}
}
|
把这句:
FD_SET(sd,&fds);
放在while内部.
FD_SET(sd,&fds);
放在while内部.