LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   How to receive DHCP broadcast messages? (https://www.linuxquestions.org/questions/programming-9/how-to-receive-dhcp-broadcast-messages-710432/)

kornerr 03-10-2009 04:04 AM

How to receive DHCP broadcast messages?
 
I try to receive any DHCP broadcast with
Code:

    sockaddr_in srvAddr,
                cliAddr;
    //int mSrvSocket = socket(AF_INET, SOCK_RAW, IPPROTO_DIVERT);
    int mSrvSocket = socket(AF_INET, SOCK_DGRAM, 0);
    if (mSrvSocket < 0)
        throw std::runtime_error("Could not create server socket");
    int broadcast = 1;
    if (setsockopt(mSrvSocket, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(broadcast)) < 0)
        throw std::runtime_error("Could not set socket be broadcast aware");
    bzero(&srvAddr, sizeof(srvAddr));
    bzero(&cliAddr, sizeof(cliAddr));
    srvAddr.sin_family = AF_INET;
    srvAddr.sin_addr.s_addr = htonl(INADDR_ANY);
    srvAddr.sin_port = htons(67);
    if (bind(mSrvSocket, (sockaddr*)&srvAddr, sizeof(srvAddr)) < 0)
        throw std::runtime_error("Could not bind the socket");
    /*
    ssize_t rcvbufsize = BUF_LEN;
    if (setsockopt(mSrvSocket, SOL_SOCKET, SO_RCVBUF, &rcvbufsize, sizeof(rcvbufsize)) < 0)
        throw std::runtime_error("Could not set new receive buffer size");
        */
    while (1) {
        socklen_t len = sizeof(cliAddr);
        ssize_t n = recvfrom(mSrvSocket, buf, BUF_LEN, 0, (sockaddr*)&cliAddr, &len);
        buf[n] = 0;
        std::cout << "Buf: " << buf;
    }

It doesn't work. When a PC with DHCP issues a request only Wireshark can see DHCP broadcast, but not me.
I tried to use no setsockopt with SO_BROADCAST. I tried to use
Code:

srvAddr.sin_addr.s_addr = htonl(INADDR_ANY);
with INADDR_BROADCAST instead of INADDR_ANY, with and without htonl. Nothing helps.
Also, I do not have iptables installed.
Thanks.

kornerr 03-11-2009 02:31 AM

It all came down to the fact I had to enable 'promisc' mode on Ethernet interface...


All times are GMT -5. The time now is 09:15 AM.