osx - How to use a local domain socket in Objective-C -


objective-c makes easy use network sockets streams doing this:

// setup comms server, assumed running on local host nshost* host = [nshost hostwithaddress:@"127.0.0.1"];  nsinputstream *istream; nsoutputstream *ostream;  [nsstream getstreamstohost:host port:_port inputstream: &istream outputstream: &ostream]; 

however, possible create , or connect local domain socket way, or objective-c provide other classes this?

if can still use nsstream , getstreamstohost, how specify file , put port number?

my research on this, far, shows many examples working tcp/ip or udp, not local domain sockets.

you can’t use -getstreamstohost:port:inputstream:outputstream: unix domain socket, no. can, however, create own nsinputstream , nsoutputstream instances; easiest way take advantage of toll-free bridging between cf(read|write)stream , ns(input|output)stream; instance:

struct sockaddr_un sun;  sun.sun_family = af_unix; strcpy (sun.sun_path, "/path/to/my/socket"); sun.sun_len = sun_len(&sun);  // server side (naive) int server_sock = socket (sock_unix, sock_stream, 0); int ret = bind (server_sock, (struct sockaddr *)&sun, sun.sun_len);  listen (server_sock, 1);               // in practice you'd specify more 1  s = accept (server_sock, null, null);  // in practice want keep calling  // client side int s = socket (sock_unix, sock_stream, 0);  int ret = connect (s, (struct sockaddr *)&sun, sun.sun_len);  cfreadstreamref readstream; cfwritestreamref writestream;  cfstreamcreatepairwithsocket (kcfallocatordefault, s, &readstream, &writestream); 

then nsinputstream , nsoutputstream can do

nsinputstream *inputstream = (__bridge_transfer nsinputstream *)readstream; nsoutputstream *outputstream = (__bridge_transfer nsoutputsteram *)outputstream; 

obviously in practice may want wrap of above in function or method in own code. also, take care sockaddr_un; sun_path member supposed have 1024 characters, in headers seems have 104 (this long-standing problem , apparently goes way bsd4.4; systems have other character counts here too). near path_max, in practice may wish write more like

struct sockaddr_un *new_unix_addr (const char *path) {   size_t len = strlen (path);   size_t bytes = sizeof (struct sockaddr_un) + len + 1                  - sizeof (((struct sockaddr_un *)0)->sun_path);   struct sockaddr_un *pun = (struct sockaddr_un *)malloc (bytes);    pun->sun_family = af_unix;   pun->sun_len = bytes;   memcpy (pun->sun_path, path, len + 1);   return pun; } 

remembering later free() it.


Comments

Popular posts from this blog

c# - How to get the current UAC mode -

postgresql - Lazarus + Postgres: incomplete startup packet -

javascript - Ajax jqXHR.status==0 fix error -