开发者

UDP sockets in ad hoc network (Ubuntu 9.10)

I am using BSD sockets in Ubuntu 9.10 to send UDP packets in broadcast with the following code:

        sock_fd = socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP);
        //sock_fd=socket(AF_INET,SOCK_DGRAM,0);
        receiver_addr.sin_family = PF_INET;
        //does not send with broadcast in ad hoc
        receiver_addr.sin_addr.s_addr = htonl(INADDR_BROADCAST);
        inet_aton("169.254.255.255",&receiver_addr.sin_addr);
        receiver_addr.sin_port = htons(port);
        int broadcast = 1;
           // this call is what allows broadcast packets to be sent:
           if (setsockopt(sock_fd, SOL_SOCKET, SO_BROADCAST开发者_Python百科, &broadcast,
               sizeof broadcast) == -1) {
               perror("setsockopt (SO_BROADCAST)");
               exit(1);
           }
        ret=sendto(sock_fd, packet, size, 0,(struct sockaddr*)&receiver_addr,sizeof(receiver_addr));

Note that is not all the code, it is only to have an idea.

The program sends all the data with INADDR_BROADCAST if I am connected to an infrastructure wireless network. However, if my laptop is connected to an ad-hoc network, it is able to receive all the data, but not to send it. I have solved the problem using the 169.254.255.255 broadcast address, but I would like to know what is going on.

Thank you in advance!


Do you have more than one adapter (i.e. wired ethernet, WLAN)?

When you send to the limited broadcast address (INADDR_BROADCAST) your IP stack uses the first adapter and sends the frame. You dont have any control about choosing a specific adapter. The IP stack has done it's job, when it sends to the first adapter found. The frame would be flooded over the whole Internet if this would not be prevented by routers. That's why UDP broadcast are not routable by default. (Exceptions exist as implemented in DHCP relays.)

When you need to send a UDP frame on a specific network, you need the network broadcast address. You did this already, when you send to 169.254.255.255 on a AUTOIP net.

The setsocket(SOL_SOCKET, SO_BROADCAST) just configures the socket to allow sending broadcast at all.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜