IOS SDK: How to check if a port is open?

I have not yet found anything on how to check if a port is open or not. I tried to implement it using the AsyncSocket class, but it always returns TRUE, although I reject all connections to this port on my server. In addition, I tried to use the isConnected AsyncSocket method, but always returns FALSE.

My code is:

 //Init socket socket=[[AsyncSocket alloc] initWithDelegate:self]; //results on TRUE always! NSLog(@"Ready"); NSError *err = nil; if(![socket connectToHost:@"10.1.2.40" onPort:25 error:&err]) { NSLog(@"Error: %@", err); } else { NSLog(@"Connected"); } //addition - results in FALSE always! if([socket isConnected]) { NSLog(@"yes, its connected"); } else { NSLog(@"not connected..."); } [socket disconnect]; 
+4
source share
1 answer

You need to make yourself a delegate and handle the onSocket: willDisconnectWithError: method. The connection is completely asynchronous, therefore, if there is no fundamental system problem (the sockets are disconnected, you passed an invalid address, etc.), then the call will always be successful if the attempt to connect the socket occurs in the background.

If this attempt fails, the onSocket: willDisconnectWithError: delegate method will be called so that you can find out that the connection attempt failed.

I'm not sure why, but the AsyncSocket class thinks that the status of the kCFStreamStatusError stream is "connected", so I suspect that is why it appears to be connected. You can follow all of this in the AsyncSocket source.

+1
source

All Articles