It is possible to interact with Darwin's BSD sockets API in all of Mac OS X's C-based application environments, including Cocoa. This API is declared primarily in the headers sys/socket.h and netinet/in.h, and is discussed at length in Unix Network Programming, by W. Richard Stevens (Prentice Hall, 1998). Core Foundation also provides an API to sockets with CFSocket. However, discussion of CFSocket is beyond the scope this book. Instead, the next section provides shows how to interact with sockets using the Foundation class NSSocketPort.
In earlier versions of Mac OS X (prior to Mac OS X 10.2), NSSocketPort was used exclusively as part of Cocoa's distributed objects architecture. NSSocketPort created sockets-based distributed objects connections across a network. However, now NSSocketPort provides a convenient alternative to the C sockets API for raw messaging.
NSSocketPort makes it possible to create sockets configured either as local listening sockets (server sockets) or sockets connected to a remote host (client sockets). The simplest way to initialize a listening socket port object is using the method initWithTCPPort:. This method takes a port number as an argument and returns an NSSocketPort object representing a TCP/IP streaming socket. If 0 is passed as the port number, then the operating system selects a port to bind to the socket.
Initialize an NSSocketPort to connect to a remote socket with the method initWithRemoteTCPPort:host:. This method takes as arguments the port number you connect to on the host specified in the second argument. A connection to the remote host is not actually established until data is sent. The hostname may be either a domain-name-like hostname, such as www.oreilly.com, or an IPv4-style address, such as 208.201.239.36.
Several of NSSocketPort's methods provide information about the socket, including:
This method returns an NSData object that contains the socket's sockaddr structure, which provides information about the sockets address.
This method returns an int specifying the protocol used by the receiver, and protocolFamily returns an int specifying the protocol family used by the receiver.
This method returns an int that identifies the receiver's socket type.
The values returned by these methods are the same as the values of the constants used in the BSD sockets API. If you're familiar with socket programming on a Unix system, you should feel right at home with NSSocketPort.
The socket method returns a native OS socket file descriptor, which can then be used with the standard C functions read and write, or to initialize an NSFileHandle. Example 6-7 demonstrates how to use NSSocketPort to create sockets.
// Local TCP/IP socket of type SOCK_STREAM listening on port 52279 NSSocketPort *sock= [[NSSocketPort alloc] initWithTCPPort:52279]; // Socket to connect to remote host sock = [[NSSocketPort alloc] initRemoteWithTCPPort:52279 host:@"10.0.1.3"];