PDA

View Full Version : Why couldn't scan the active port in my PC?



leetow2003
07-09-2011, 08:29 AM
I find the active port in my PC using command netstat -an,
but when I run my codes,it couldn't find any active port,
and I think my codes are not good,who could correct it?thank you very much.
Look:


static char* ip="192.168.1.6";
int main()
{
int sk;
struct sockaddr_in addrs;
struct in_addr ina;
int iPort,iRet;
int flags;

//server IP
bzero(&addrs,sizeof(struct sockaddr_in));
inet_aton(ip,&ina);
addrs.sin_family=AF_INET;
addrs.sin_addr=ina;

for(iPort=0;iPort<200;iPort++)
{
//creat socket about SOCK_STREAM
sk=socket(AF_INET,SOCK_STREAM,0);
if(sk<0)
{
perror("socket error");
return -1;
}
else
{
flags = fcntl(sk,F_GETFL,0);
fcntl(sk,F_SETFL,flags | O_NONBLOCK);//set NONBLOCK
}

addrs.sin_port=htons(iPort);
iRet=connect(sk,(struct sockaddr*)&addrs,sizeof(struct sockaddr));
if(iRet<0)
{
close(sk);
continue;
}
else
{
printf("active port=%d\n",iPort);
close(sk);
}
}
close(sk);
return 0;
}

anduril462
07-09-2011, 11:37 AM
Learn to use GDB, and you could've run through your code and found where the problem is. Then you would have realized that adding the following perror call would tell you exactly what the problem is.


if(iRet<0)
{
perror("connect");
close(sk);
continue;
}