Thread: Why couldn't scan the active port in my PC?

  1. #1
    Registered User
    Join Date
    Jun 2011
    Posts
    50

    Why couldn't scan the active port in my PC?

    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:
    Code:
    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;
    }

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    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.
    Code:
    if(iRet<0)
    {
        perror("connect");
        close(sk);
        continue;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. program that i couldn't understand
    By elton_fan in forum C Programming
    Replies: 9
    Last Post: 03-24-2007, 03:18 PM
  2. Why couldn't this have come out Before christmas?
    By Scribbler in forum A Brief History of Cprogramming.com
    Replies: 9
    Last Post: 01-12-2005, 11:03 AM
  3. Replies: 4
    Last Post: 03-23-2003, 05:40 AM
  4. about scan 7-segment display via parallel port
    By mobdawg in forum C Programming
    Replies: 4
    Last Post: 09-11-2002, 06:11 AM
  5. Couldn't stop!
    By cockroach007 in forum C Programming
    Replies: 1
    Last Post: 10-13-2001, 08:52 AM