Skip navigation.
 
mlRe: NSSocketPort bug?
FROM : Douglas Davidson
DATE : Wed Dec 15 21:42:28 2004

On Dec 15, 2004, at 2:30 AM, Malte wrote:


> This is a kind of follow up to the thread i've started earlier asking
> for help in the BSD <--> Cocoa Socket thing.
> I narrowed something down that looks to me like a bug, but maybe i'm
> just doing something wrong.
> Please give me some feedback on this:
>
> When i call:
>    NSSocketPort * sockPort = [[NSSocketPort alloc]
> initWithTCPPort:12345];
>    int socketFD = [sockPort socket];
>    NSLog(@"server socketFD: %i", socketFD);
> The NSLog message gives me a positive integer (i.e. 8 in this case)
> just like a fileDescriptor should be
>
> However, when i substitute the above with this:
>    NSSocketPort * sockPort = [[NSSocketPort alloc]
> initRemoteWithTCPPort:12345 host:@"192.168.1.1"];
>    int socketFD = [sockPort socket];
>    NSLog(@"server socketFD: %i", socketFD);
> The socketFD is *ALWAYS*  ==  -1 !!
>
> Can anyone verify this? Is this a bug or am i just doing something
> horribly wrong?


You're doing something wrong.  I didn't see your earlier thread, but
here's what's going on. NSSocketPorts come in two types:  local ports,
which are represented by a socket on the local machine, and remote
ports, which represent a reference to a socket on some other machine. 
In the first instance, you have a local port, which does have a file
descriptor for its socket.  In the second instance, you have a remote
port--and you can't get a file descriptor for a socket on some other
machine.

Before you use NSSocketPort, make sure you understand what it is.  It's
not a general-purpose BSD socket wrapper.  NSSocketPort is a subclass
of NSPort that is implemented using sockets.  If you don't understand
the superclass, NSPort, then you certainly don't understand the
subclass, NSSocketPort.

NSPort subclasses are intended primarily for use with Distributed
Objects.  They can be used on their own for sending NSPortMessages from
one Cocoa process to another, but it's usually much more convenient to
use Distributed Objects than to use an NSPort directly.  NSSocketPort
cannot be used for communicating with non-Cocoa processes, and its
primary purpose is to serve as the basis of a Distributed Objects
connection.  The main reason that it exposes the file descriptor at all
is so that, if necessary, the client can make setsockopt calls on it;
otherwise the -socket method is rarely used.

There are many alternatives to NSSocketPort.  If your intent is to use
BSD sockets, but you want one to act as a run loop source, then you can
use the lower-level CFSocket.  If you simply want a general-purpose
networking class, look at NSStream.

Douglas Davidson

Related mailsAuthorDate
mlNSSocketPort bug? Malte Dec 15, 11:30
mlRe: NSSocketPort bug? João Pavão Dec 15, 15:03
mlRe: NSSocketPort bug? Douglas Davidson Dec 15, 21:42
mlRe: NSSocketPort bug? Malte Dec 15, 22:56
mlRe: NSSocketPort bug? Dustin Voss Dec 16, 04:25