问题
I have not found anything yet on how to check if a port is open or not. I tried to realize it with the AsyncSocket class but it returns always TRUE although I reject all connections to that port on my server.
Additionally, I tried to use the isConnected
method of AsyncSocket but that always returns FALSE.
My code so far:
//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];
回答1:
You need to make yourself the delegate and handle the onSocket:willDisconnectWithError: method. The connection is entirely async so unless there is a fundamental system problem (sockets are disabled, you passed in an invalid address, etc) then that call will always succeed while the socket connection attempt happens in the background.
If that attempt fails, the onSocket:willDisconnectWithError: delegate method will get called so you can know the connection attempt failed.
I'm not sure why but the AsyncSocket class considers the kCFStreamStatusError stream status to be "connected" so I suspect that is why it shows up as connected. You can follow all this in the source of AsyncSocket.
来源:https://stackoverflow.com/questions/6329723/ios-sdk-how-can-i-check-if-a-port-is-open