sockaddr_un实例--监听与连接UNIX域socket

/* 要点:sockaddr_un
 * 功能:监听UNIX域socket 
 * 成功:返回新生成的套接字文件描述符 
 * 失败:返回-1 
 */
int std_listen_unix(const char *socketfile)
{
    int fd = 0, len = 0, operate_ret = OPERATE_SUCCESS;
    struct sockaddr_un serv;

    if((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
    {
        STD_DEBUG_PRINT("socket failed! %s\n", strerror(errno));
		operate_ret = OPERATE_FAILED;
        goto ret_lable;
    }
	
    unlink(socketfile);	/***********************/

    len = strlen(socketfile);

    if(len > 107)
    {
        DEBUG_PRINT ("socket file len is too long!");
		operate_ret = OPERATE_FAILED;
        goto ret_lable;
    }

    memset (&serv, 0, sizeof(serv));
    serv.sun_family = AF_UNIX;
    strncpy (serv.sun_path, socketfile, len);

    len += offsetof(struct sockaddr_un, sun_path); /**********/

    if(bind(fd, (struct sockaddr *)&serv, len) < 0)
    {
        DEBUG_PRINT ("bind failed!");
        operate_ret = OPERATE_FAILED;
        goto ret_lable;
    }

    if(listen(fd, 10) < 0)
    {
        DEBUG_PRINT ("listen failed!");
        operate_ret = OPERATE_FAILED;
        goto ret_lable;
    }
	
    return (fd);	/************************/

ret_lable:
	if (fd >= 0)
	{
		close(fd);
	}
	
    return operate_ret;
}


/* 要点:sockaddr_un
 * 功能:连接到UNIX域socket 
 * 成功:返回新生成的套接字文件描述符 
 * 失败:返回-1 
 */
int std_connect_unix(const s8 *socketfile)
{
    int sock = 0, ret = 0, opt = 0;
    size_t len = 0;
    struct sockaddr_un srv_sock;
	
    if( (sock = socket(AF_UNIX, SOCK_STREAM, 0)) < 0 )
    {
        DEBUG_PRINT("socket failed!%s\n", strerror(errno));
        return OPERATE_FAILED;
    }
    
    len = strlen (socketfile);
    memset (&srv_sock, 0, sizeof(struct sockaddr_un));
    srv_sock.sun_family = AF_UNIX;
    strncpy (srv_sock.sun_path, socketfile, len);
    
    len += offsetof (struct sockaddr_un, sun_path);
    
    if((ret = connect(sock, (struct sockaddr *)&srv_sock, len)) < 0 )
    {
        DEBUG_PRINT ("connect failed: %d\n", ret);
        close (sock);
        return OPERATE_FAILED;
    }
    
    opt = 1;
    setsockopt (sock, SOL_SOCKET, SO_KEEPALIVE, &opt, sizeof(opt));
    
    return sock;
}


你可能感兴趣的:(sockaddr_un实例--监听与连接UNIX域socket)