ccplusplus.com
Learn C, C++ Concepts
Friday, February 17, 2012
af_unix example
/************************************************************************* * File : af_unix.c * Author : Saurabh Gupta * Desc : af_unix example * Source : http://www.ccplusplus.com/2011/07/socket.html * Created : 12:17 PM Friday, February 17, 2012 *************************************************************************/ #include
#include
#include
#include
#include
#include
#include
#include
#include
/* * This function reports the error and * exits back to the shell: */ static void displayError(const char *on_what) { perror(on_what); exit(1); } int main(int argc, char **argv, char **envp) { int z; /* Status return code */ int sck_unix; /* Socket */ struct sockaddr_un adr_unix;/* AF_UNIX */ int len_unix; /* length */ const char pth_unix[] = "/tmp/my_sock";/* pathname */ /* * Create a AF_UNIX (aka AF_LOCAL) socket: */ sck_unix = socket(AF_UNIX,SOCK_STREAM,0); if ( sck_unix == -1 ) { displayError("socket()"); } /* * Here we remove the pathname for the * socket, in case it existed from a * prior run. Ignore errors (it might * not exist). */ unlink(pth_unix); /* * Form an AF_UNIX Address: */ memset(&adr_unix,0, sizeof adr_unix); adr_unix.sun_family = AF_UNIX; strncpy(adr_unix.sun_path,pth_unix, sizeof adr_unix.sun_path-1) [sizeof adr_unix.sun_path-1] = 0; len_unix = SUN_LEN(&adr_unix); /* * Now bind the address to the socket: */ z = bind(sck_unix, (struct sockaddr *)&adr_unix, len_unix); if ( z == -1 ) { displayError("bind()"); } /* * Display all of our bound sockets: */ system("netstat -pa --unix 2>/dev/null | sed -n '/^Active UNIX/,/^Proto/p; /af_unix/p'"); /* * Close and unlink our socket path: */ close(sck_unix) ; unlink(pth_unix); return 0; } /* * OUTPUT * [sgupta@rhel6x86 domain-address-family]$ gcc af_unix.c -o af_unix [sgupta@rhel6x86 domain-address-family]$ ./af_unix Active UNIX domain sockets (servers and established) Proto RefCnt Flags Type State I-Node PID/Program name Path unix 2 [ ] STREAM 76258 4510/af_unix /tmp/my_sock [sgupta@rhel6x86 domain-address-family]$ */
No comments:
Post a Comment
Newer Post
Older Post
Home
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment