int recv_msg(char *ip , unsigned short port , char *mult_ip )
{
//建立通讯套接字
int fd = socket( PF_INET , SOCK_DGRAM , 0 )
if( -1 == fd )
{
perror("socket failed")
return -1
}
//设置地址重用和接收多播
{
int reuse = 1
struct ip_mreqn mult_addr = {0}
mult_addr.imr_multiaddr.s_addr = inet_addr( mult_ip )
mult_addr.imr_address.s_addr = inet_addr( ip )
if( -1 == setsockopt( fd , IPPROTO_IP , IP_ADD_MEMBERSHIP ,
&mult_addr , sizeof(mult_addr)))
{
perror("setsockopt add failed")
goto _out
}
if( -1 == setsockopt( fd , SOL_SOCKET, SO_REUSEADDR,
&reuse , sizeof(reuse) ) )
{
perror("setsockopt reuse failed")
}
}
//绑定地址和端口
{
struct sockaddr_in addr = {0}
addr.sin_family = PF_INET
addr.sin_port = htons( port )
addr.sin_addr.s_addr = INADDR_ANY
if( -1 == bind( fd , (struct sockaddr*)&addr ,
sizeof(addr) ) )
{
perror("bind failed")
goto _out
}
}
//接收信息
while(1)
{
char buf[128] = {0}
int ret = 0
struct sockaddr_in client_addr = {0}
int len = sizeof(client_addr)
ret = recvfrom( fd , buf , sizeof(buf), 0 ,
(struct sockaddr*)&client_addr ,
&len )
//被信号中断则重启
if( (-1 == ret)&&(EINTR ==errno ))
{
continue
}
else if( -1 ==ret )
{
perror("recvfrom failed")
goto _out
}
else if( ret >0 )
{
printf("%s\n" , buf )
}
usleep( 100*1000 )
}
_out:
if( fd >= 0)
{
close( fd )
}
return 0
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)