wiki:unix_socket_server_client
- 1
#include <stdio.h> #include <sys/types.h> #include <sys/un.h> #include <sys/socket.h> #include <errno.h> #include <string.h> #include <stdlib.h> #define UNIX_PATH_MAX 128 int UClient(const char *sockname) { int sockfd; struct sockaddr_un addr; int rc; if (sockname == NULL || strlen(sockname) > UNIX_PATH_MAX) { printf("Invalid sockname\n"); return (-1); } sockfd = socket(AF_UNIX, SOCK_STREAM, 0); if (sockfd < 0) { printf("socket error: %s\n", strerror(errno)); return (-1); } memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; memcpy(addr.sun_path, sockname, strlen(sockname)); if (connect(sockfd, (struct sockaddr*) &addr, sizeof(addr)) < 0) { printf("connect error: %s\n", strerror(errno)); close(sockfd); return (-1); } return (sockfd); } int UServer(const char *sockname) { int sockfd; struct sockaddr_un addr; if (sockname == NULL || strlen(sockname) > UNIX_PATH_MAX) { printf("Invalid sockname\n"); return (-1); } unlink(sockname); sockfd = socket(AF_UNIX, SOCK_STREAM, 0); if (sockfd < 0) { printf("socket error: %s\n", strerror(errno)); return (-1); } memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; memcpy(addr.sun_path, sockname, strlen(sockname)); if (bind(sockfd, (struct sockaddr *) &addr, sizeof(addr)) == 0) { if (listen(sockfd, 5) == 0) return (sockfd); } close(sockfd); printf("connect error: %s\n", strerror(errno)); return (-1); } /* end of file */
wiki/unix_socket_server_client.txt · Last modified: 2007/06/24 00:16 by mirnshi