Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Xino

macrumors member
Original poster
Sep 5, 2008
36
0
How can I check if a port of a given host is open?

I've searched the developer reference but couldn't find anything useful...
Application is written in Objective-C / Cocoa.

Thanks for your help
 

yeroen

macrumors 6502a
Mar 8, 2007
944
2
Cambridge, MA
You will have to try connecting to the remote address and port (I'm assuming you want to connect to a remote TCP Server).

At the lowest level BSD sockets C API, the connect() call returns a -1 on failure and sets the global errno variable to ECONNREFUSED when no one is listening on the remote address.

NSStream and CFSocket will return an error code or error object, but although these may be enough to say that the connection failed, I'm not sure they'll tell you why it failed.

The good news is you can assume that both Cocoa and Core Foundation use BSD sockets underneath the hood and so you can check the errno variable after a failed connection attempt as you would had you written this using the sockets API versus Cocoa/CoreFoundatation.

(errno should be thread-safe on OS-X)

or maybe NSError will translate errno for you:

Handling Stream Errors

try it and find out
 

ChrisA

macrumors G5
Jan 5, 2006
12,578
1,694
Redondo Beach, California
How can I check if a port of a given host is open?

I've searched the developer reference but couldn't find anything useful...
Application is written in Objective-C / Cocoa.

Thanks for your help[/QUOTE

From the terminal the "telnet" works well. For example I know port 80 is open on my computer. I can test this

telnet localhost 80
Trying ::1...
Connected to localhost.
Escape character is '^]'.

but I know port 81 is not
telnet localhost 81
Trying ::1...
telnet: connect to address ::1: Connection refused


From C. Simply try to connect() and see what you get. read the "connect"
man page. The man page tells you about the return codes returned by
connect(). if you get ECONNREFUSED then the port is not open.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.