UNIX域socket编程

创建UNIX域服务端

dts_uint32 COperatingStatusNotify::CreateUnixSocket()

{
m_iFd = socket( PF_UNIX,SOCK_STREAM,0 );
if ( m_iFd < 0 )
{
GAL_ERROR_PRINT << "create PF_UNIX SOCK_STREAM error : %m";
GAL_ERROR << "create PF_UNIX SOCK_STREAM error : " << errno;
return -1;
}


CDTS_Auxiliary::DTS_socket_set_option( m_iFd,DTS_SOCKOPT_SNDBUF,40960 );


struct sockaddr_un stUnaddr;
memset( &stUnaddr,0,sizeof(stUnaddr) );
stUnaddr.sun_family = AF_LOCAL;
strncpy( stUnaddr.sun_path+1,m_szPath,sizeof(stUnaddr.sun_path)-1 );
unlink( m_szPath );


socklen_t tLen = sizeof(stUnaddr);//strlen(stUnaddr.sun_path) + offsetof( struct sockaddr_un, sun_path );


if ( bind( m_iFd,(struct sockaddr*)&stUnaddr,tLen ) == -1 )
{
GAL_ERROR_PRINT << "AF_LOCAL bind " << stUnaddr.sun_path+1 << " error : %m";
GAL_ERROR << "AF_LOCAL bind " << stUnaddr.sun_path+1 << errno;
close( m_iFd );
m_iFd = DTS_SOCKET_NULL;


return -1;
}


if ( listen( m_iFd,5 ) != 0 )
{
GAL_ERROR_PRINT << "AF_LOCAL listen " << stUnaddr.sun_path+1 << " error : %m";
GAL_ERROR << "AF_LOCAL listen " << stUnaddr.sun_path+1 << " error : " << errno;
close( m_iFd );
m_iFd = DTS_SOCKET_NULL;


return -1;
}


GAL_DEBUG_PRINT << "AF_LOCAL listen on " << stUnaddr.sun_path << " success";


return 0;

}

创建UNIX域客户端

dts_uint32 CRead_Notifyd::ConnectUnixSocket()
{
m_iFd = socket( PF_UNIX,SOCK_STREAM,0 );
if ( m_iFd < 0 )
{
std::cout << "cannot create PF_UNIX socket error = " << errno << std::endl;
return -1;
}


//std::cout << "create PF_UNIX socket = " << m_iFd << std::endl;


struct sockaddr_un srv_addr;
memset( &srv_addr,0,sizeof(srv_addr) );
srv_addr.sun_family = AF_LOCAL;
strncpy( srv_addr.sun_path+1,m_szPath,sizeof(srv_addr.sun_path)-1 );
unlink( m_szPath );


CDTS_Auxiliary::DTS_socket_set_option( m_iFd,DTS_SOCKOPT_RCVBUF,40960 );


socklen_t tLen = sizeof( srv_addr );//strlen(srv_addr.sun_path) + offsetof( struct sockaddr_un, sun_path );


if ( connect( m_iFd,(struct sockaddr*)&srv_addr,tLen ) == -1 )
{
std::cout << m_iFd << " cannot connect AF_LOCAL error = " << errno << " len = " << tLen << " " << srv_addr.sun_path+1 << std::endl;


close( m_iFd );
m_iFd = DTS_SOCKET_NULL;


return -1;
}

return 0;
}

转载于:https://my.oschina.net/u/728887/blog/170789

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值