Question

For some data transfer via UDP I am using the async_receive_from-function from boost. My receiving function is

        udp::socket socket_;
        udp::endpoint remote_endpoint_;
        boost::array<char, 200> recv_buffer_;

        void start_receive()
        {
            std::fill(recv_buffer_.begin(), recv_buffer_.end(), '\0');
            socket_.async_receive_from(boost::asio::buffer(recv_buffer_), remote_endpoint_, boost::bind(&udp_server_ping::handle_receive, this, boost::asio::placeholders::error));
        }

        void handle_receive(const boost::system::error_code& error)
        {
            if (!error || error == boost::asio::error::message_size)
            {
                for(int i = 0; i < 200; i++)
                    std::cout << recv_buffer_.c_array()[i];
                std::cout << '\n';
                for(auto it = boost::begin(recv_buffer_); it != boost::end(recv_buffer_); ++it)
                    std::cout << *it;
                std::cout << '\n';
                switch(recv_buffer_.c_array()[0])
                {
                case '#':
                    {
                        got_ping = true;
                        std::cout << "Gotcha!\n";
                        break;
                    }
                case '$':
                    {
                        std::vector<char> char_buf(boost::begin(recv_buffer_), boost::end(recv_buffer_));
                        std::stringstream ss(std::string(char_buf.begin(), char_buf.end()));
                        std::vector<std::string> ip_list;
                        std::string ip;
                        std::cout << "Char_buf is: ";
                        for(auto it = boost::begin(recv_buffer_); it != boost::end(recv_buffer_); ++it)
                            std::cout << *it;
                        std::cout << "\nStringstream is: " << ss << '\n';
                        while(std::getline(ss, ip, '$'))
                        {
                            ip_list.push_back(ip);
                        };
                        ip_adr_ccd = ip_list[0];
                        ip_adr_daisy = ip_list[1];
                        std::cout << "ip_adr_ccd is: " << ip_list[1] << " and ip_adr_daisy is: " << ip_list[2] << '\n';
                        ip_adr_display.push_back(ip_list[3]);
                        break;
                    }
                default:
                    break;

                start_receive();
                }

while my transmitting function is

DLL void transmit_ip(void)
{
    WORD wVersionRequested;
    WSADATA wsaData;
    int err;

    wVersionRequested = MAKEWORD( 2, 2 );

    err = WSAStartup( wVersionRequested, &wsaData );
    if ( err != 0 ) {
        /* Tell the user that we could not find a usable */
        /* WinSock DLL.                                  */
        return;
    }


    struct sockaddr_in sa;
    struct hostent     *hp;
    SOCKET s;
    std::string ip_adr;
    if(Use == 'T')
        ip_adr = ip_adr_ccd;
    else
    {
        if(Use == 'S')
            ip_adr = ip_adr_daisy;
        else
            ip_adr = ip_adr_display[0];
    };
    //Debug
    //std::cout << "Pinging ip: " << ip_adr << '\n';
    hp = gethostbyname(ip_adr.c_str());
    if (hp == NULL) /* we don't know who this host is */
        return;

    memset(&sa,0,sizeof(sa));
    memcpy((char *)&sa.sin_addr, hp->h_addr, hp->h_length);   /* set address */
    sa.sin_family = hp->h_addrtype;
    sa.sin_port = htons((u_short)PORTNUM_UDP_OUT);

    s = socket(hp->h_addrtype, SOCK_DGRAM, 0);
    if (s == INVALID_SOCKET)
        return;
    std::string tx_str = '$' + ip_adr_ccd + '$' + ip_adr_daisy + '$' + retLocalIP() + '$';
    //char str[] = "$127.0.0.1$128.0.0.1$129.0.0.1$";
    std::cout << "tx_str is: " << tx_str << '\n';
    char * buffer = new char[tx_str.length() + 1];
    std::strcpy(buffer, tx_str.c_str());
    int ret;
    ret = sendto( s, buffer, sizeof(buffer), 0, (struct sockaddr *)&sa, sizeof(sa));
    delete buffer;

}

When I am using the str[] for transmitting, everything is fine, but when I want to transmitt my tx_str, the receiver crashes at once and only shows $192 as received data. What am I doing wrong for creating a buffer overflow?

Was it helpful?

Solution

When buffer is a char*, sizeof(buffer) returns the size of a pointer, rather than the length of the pointed to string. It appears as though the system on which it is compiled uses 4 bytes for a pointer, hence only 4 characters are transmitted. Upon receiving the 4 bytes, handle_receive() invokes undefined behavior when it attempts to access an invalid index in ip_list, as the code assumes 3 strings are always extracted from the receive message.

To resolve the problem, explicitly provide the buffer size to sendto() rather than using sizeof(). Change:

ret = sendto( s, buffer, sizeof(buffer), 0, ...)

to:

ret = sendto( s, buffer, tx_str.length() + 1, 0, ...)

It may also be worth considering checking input and verifying ip_list is the expected size before indexing into it.


char[] and char* are different types. In the case of char*, sizeof() will return the size of a pointer on the given system and not the length of the string pointed to by the pointer. On the other hand, for char[], sizeof() will return the size of the array. For example:

#include <iostream>

int main()
{
    char str[] = "123456789ABCDEF";
    char* buffer = new char[100];
    std::cout << "char[] size = " << sizeof(str) << "\n"
                 "char* size = " << sizeof(buffer) << std::endl;
}

Results in:

char[] size = 16
char* size = 8
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top