iOS SDK: How can I check if a port is open?

巧了我就是萌 提交于 2019-12-20 00:43:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!