- 论坛徽章:
- 0
|
#include "unp.h"
#define MAXPORT 1000
extern int errno;
int main(int argc,char **argv){
int sockfd,i,ret;
struct sockaddr_in servaddr;
if (argc != 2)
err_quit("usage: a.out <IPaddress>");
if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
err_sys("socket error");
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
if (inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <= 0)
err_quit("inet_pton error for %s", argv[1]);
for(i=1;i<MAXPORT;i++){
printf("conneting to port %d \n",i);
servaddr.sin_port = htons(i);
if (ret=connect(sockfd, (SA *) &servaddr, sizeof(servaddr)) >= 0)
{
printf("port %d is open \n",i);
}
printf("return %d\n",ret);
printf("errno %d,msg %s",errno,strerror(errno));
}
exit(0);
}
|
返回结果:
conneting to port 1
return 0
errno 111,msg Connection refusedconneting to port 2
return 0
errno 111,msg Connection refusedconneting to port 3
return 0
errno 111,msg Connection refusedconneting to port 4
return 0
errno 111,msg Connection refusedconneting to port 5
return 0
errno 111,msg Connection refusedconneting to port 6
return 0
errno 111,msg Connection refusedconneting to port 7
return 0
errno 111,msg Connection refusedconneting to port 8
return 0
errno 111,msg Connection refusedconneting to port 9
return 0
errno 111,msg Connection refusedconneting to port 10
return 0
errno 111,msg Connection refusedconneting to port 11
return 0
errno 111,msg Connection refusedconneting to port 12
return 0
errno 111,msg Connection refusedconneting to port 13
port 13 is open
return 1
errno 111,msg Connection refusedconneting to port 14
return 0
errno 106,msg Transport endpoint is already connectedconneting to port 15
return 0
errno 106,msg Transport endpoint is already connectedconneting to port 16
return 0
errno 106,msg Transport endpoint is already connectedconneting to port 17
return 0
errno 106,msg Transport endpoint is already connectedconneting to port 18
return 0
。奇怪的是它连接失败为什么不返回-1,而返回0.而成功返回的不是0,却是1.这和unp书上的意思相左啊。网上其他的也都是提到返回-1为出错。0为正常。 |
|