Network code notes

UDP报文接收BUF长度小于实际报文长度,剩余的会被丢弃。


发送广播时需要设置:
    int option = 1;
    setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &option, sizeof(option));

接收组播时需要加入组:
    /* join ipv4 group */
    struct ip_mreq mreq;
    mreq.imr_multiaddr.s_addr = inet_addr(NT_GROUP_ADDR_IPV4);
    mreq.imr_interface.s_addr = htonl(INADDR_ANY);
    setsockopt(listenFd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq));
    
    /* join ipv6 group */    
    struct ipv6_mreq mreq6;
    inet_pton(AF_INET6, NT_GROUP_ADDR_IPV6, &mreq6.ipv6mr_multiaddr);
    mreq6.ipv6mr_interface = htonl(INADDR_ANY);
    setsockopt(listenFd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP,(char *)&mreq6,sizeof(mreq6));

IPv6监听socket默认同时接受ipv4和ipv6连接,bind会失败,绑定前要设置只接受IPv6连接:
    int option = 1;
    setsockopt(listenFd, IPPROTO_IPV6, IPV6_V6ONLY, &option, sizeof(option));
 

你可能感兴趣的:(linux)