// CDomain.h
#ifndef _DOMAIN_H_
#define _DOMAIN_H_
#include <stdio.h>
#include <string.h>
#include <unistd.h>
class CDomain{
public:
int create_domain_socket(const char *path);
int unix_connect(char *client_path, char *server_path);
private:
};
#endif
=================================================================
// CDomain.cpp
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/un.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/syscall.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include "domain.h"
int CDomain::create_domain_socket(const char *path)
{
int socket_fd = 0;
struct sockaddr_un addr;
int ret = 0;
if(path == NULL)
{
return -1;
}
socket_fd = socket(AF_LOCAL, SOCK_DGRAM, 0);
if(socket_fd < 0)
{
return -1;
}
bzero(&addr, sizeof(struct sockaddr_un));
addr.sun_family = AF_LOCAL;
strcpy(addr.sun_path, path);
addr.sun_path[sizeof(addr.sun_path) - 1] = 0;
unlink(path);
ret = bind(socket_fd, (struct sockaddr *)&addr, sizeof(struct sockaddr_un));
if(ret != 0)
{
close(socket_fd);
return -1;
}
return socket_fd;
}
int CDomain::unix_connect(char *client_path, char *server_path)
{
struct sockaddr_un servaddr, g_cliaddr; //socket连接变量
int sockfd; //socket连接描述
int ret = -1;
if(NULL == client_path || NULL == server_path)
{
return -1;
}
sockfd = socket( AF_LOCAL, SOCK_DGRAM, 0 );
if ( sockfd < 0 )
{
return -1;
}
//清空连接记录
bzero( &servaddr, sizeof( servaddr ) );
bzero( &g_cliaddr, sizeof(g_cliaddr) );
//注册客户
g_cliaddr.sun_family = AF_LOCAL;
strcpy( g_cliaddr.sun_path, client_path );
unlink( client_path );
//绑定socket连接信息,如果绑定失败则返回error
if ( -1 == bind( sockfd, (struct sockaddr*)&g_cliaddr, sizeof( g_cliaddr ) ) )
{
goto result;
}
//注册域
servaddr.sun_family = AF_LOCAL;
strcpy( servaddr.sun_path, server_path );
//绑定信息,失败则返回error
if ( -1 == connect(sockfd, (struct sockaddr *)&servaddr, sizeof( servaddr ) ) )
{
goto result;
}
ret = 0;
result:
if(ret < 0)
{
close(sockfd);
return -1;
}
return sockfd;
}
========================================================
// client.cpp
#include "domain.h"
int main(int argc, char *argv[])
{
if(argc < 2)
{
printf("please input 2 param\n");
return -1;
}
int len = -1;
char buf[1024] = {"wahahahahah"};
CDomain client;
char client_path[] = {"tanxiaohai11"};
char server_path[] = {"tanhuifang"};
int fd = client.unix_connect(client_path, server_path);
if(fd < 0)
{
printf("err fd\n");
return 0;
}
while(1)
{
len = write(fd, buf, sizeof(buf));
if(0 < len)
{
printf("T -----write success len[%d]\n", len);
}
usleep(2000*1000);
}
return 0;
}
===========================================
//server.cpp
#include "domain.h"
int main()
{
int len = -1;
char buf[1024] = {};
CDomain client;
char client_path[] = {"tanxiaohai"};
char server_path[] = {"tanhuifang"};
int fd = client.create_domain_socket(server_path);
if(fd < 0)
{
printf("err fd\n");
return 0;
}
while(1)
{
len = read(fd,buf,1024);
if(0 < len)
{
printf("T --server recv---[%s]\n", buf);
}
usleep(20*1000);
}
return 0;
}