linux基础之 创建一个UDP socket

UDP socket

int bind_server_udp1(int server_s)
{
	struct sockaddr_in local_addr;
	memset(&local_addr,0,sizeof(local_addr));//set 0 for everything
	local_addr.sin_family = AF_INET;//AF_INET(又称 PF_INET)是 IPv4 网络协议的套接字类型,AF_INET6 则是 IPv6 的;而 AF_UNIX 则是 Unix 系统本地通信
	local_addr.sin_addr.s_addr = htonl(INADDR_ANY);//INADDR_ANY就是指定地址为0.0.0.0的地址,这个地址事实上表示不确定地址,或“所有地址”、“任意地址”
	local_addr.sin_port = htons(3702);

	/* Give the socket FD the local address ADDR (which is LEN bytes long).
		将一本地地址与一套接口捆绑  
	int bind (int __fd, __CONST_SOCKADDR_ARG __addr, socklen_t __len);
	*/
	return bind(server_s,(struct sockaddr*)&local_addr,sizeof(local_addr));

}
static int create_server_socket_udp(void)
{
	int server_udp;
	unsigned char one = 1;
	int sock_opt = 1;
	
	//server_udp = socket(PF_INET, SOCK_DGRAM, 0);
	server_udp = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (server_udp == -1) {
		printf("unable to create socket\n");
	}

	/* reuse socket addr, SO_REUSERADDR 允许重用本地地址和端口 int充许绑定已被使用的地址(或端口号)*/
	if ((setsockopt(server_udp, SOL_SOCKET, SO_REUSEADDR, (void *) &sock_opt,sizeof (sock_opt))) == -1) {
		printf("setsockopt\n");
	    }
	/*IP_MULTICAST_LOOP组播组中的成员自己也会收到它向本组发送的报文。这个选项用于选择是否激活这种状态。*/
	if ((setsockopt(server_udp, IPPROTO_IP, IP_MULTICAST_LOOP,&one, sizeof (unsigned char))) == -1) {
		printf("setsockopt\n");
	    }


	/* IPv4 multicast request. IP_ADD_MEMBERSHIP struct ip_mreq 加入到组播组中 */
	struct ip_mreq mreq;
	mreq.imr_multiaddr.s_addr = inet_addr("239.255.255.250");
	mreq.imr_interface.s_addr = htonl(INADDR_ANY);

	if(setsockopt(server_udp,IPPROTO_IP,IP_ADD_MEMBERSHIP,&mreq,sizeof(mreq))==-1){
		perror("memberchip error\n");
	}
	return server_udp;
}


你可能感兴趣的:(linux基础之 创建一个UDP socket)