#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define MINPORT 0
#define MAXPORT 1000
int main(int argc,char **argv)
{
int fd[MAXPORT];
int flags,n,i,rst,maxfd,count=0;
int port[MAXPORT];
struct sockaddr_in addr[MAXPORT];
fd_set rset,wset;
struct timeval tm;
int addrsize=sizeof(struct sockaddr);
struct servent *sent;
FD_ZERO(&rset);
FD_ZERO(&wset);
tm.tv_sec=5;
tm.tv_usec=0;
for(i=MINPORT;i
{
if((fd[i]=socket(AF_INET,SOCK_STREAM,0))==-1)
{
perror("Socket");
exit(-1);
}
/* 设置fd为非阻塞 */
flags=fcntl(fd[i],F_GETFL,0);
fcntl(fd[i],F_SETFL,flags|O_NONBLOCK);
port[i]=i+1;
bzero((struct sockaddr*)&addr[i],addrsize);
addr[i].sin_family=AF_INET;
addr[i].sin_addr.s_addr=inet_addr(argv[1]);
addr[i].sin_port=htons((short)port[i]);
if((n=connect(fd[i],(struct sockaddr *)&addr[i],addrsize))<0)
if(errno!=EINPROGRESS)
{printf("Connecting 1 error!\n"); exit(1);}
else if(n==0)
{ //This case may be happen on localhost
printf("Connecting 1 success! \n");
exit(0);
}
FD_SET(fd[i],&rset);
}
wset=rset;
sleep(5);
rst=select(MAXPORT+3, &rset,&wset,NULL,&tm);
switch (rst) {
case -1:
perror("Select error"); exit(-1);
case 0:
for(i=MINPORT;i
close(fd[i]);
printf("Timed Out!\n");
break;
default:
for(i=MINPORT;i
{
if (FD_ISSET(fd[i],&rset)||FD_ISSET(fd[i],&wset)) {
int error;
socklen_t len = sizeof (error);
if(getsockopt(fd[i],SOL_SOCKET,SO_ERROR,&error,&len) < 0)
{
printf ("getsockopt fail,connected fail\n");
return -1;
}
if(error==0)
{
if((sent=getservbyport(htons(i+1),"tcp"))==NULL)
{
printf("Unknown service(port %d) is available. \n",i+1);
}
else {
printf("%s\tservice(port %d) is avilable. \n",sent->s_name,i+1);
}
count++;
}
}
close(fd[i]);
}
}
if(count==0)
printf("There is no port open or the domain has down!\n");
return 0;
}