Overflow while converting domain name to ip address

Hello all,

ive just written a function to tell the ipv4 of any domain like f.ex "google.com", and for linux, it yust works fine. But now i shwitched to windows and do get an bufferoverflow all the time. It turned out, that i cannot access hostent *raw_list after assignment without an overflow. Any advice?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <winsock2.h>
#include <winsock.h>
#include <windows.h>
#include <ws2tcpip.h>
#include <unistd.h>

// ...

char *getipbydom(const char *domain)
{
    char *target_ip{nullptr};
    struct in_addr *host_addr;
    struct hostent *raw_list = gethostbyname(domain);

    for (int i = 0; raw_list->h_addr_list[i] != 0; i++)
    {
        host_addr = (in_addr *) raw_list->h_addr_list[i];
        target_ip = inet_ntoa(*host_addr);
    }
    return target_ip;
}


With kind reagrds,

Luke
Last edited on
There's an example here:
https://docs.microsoft.com/en-us/windows/win32/api/winsock/ns-winsock-hostent

At first look, the only difference seems to be before L19:

 
    if (raw_list->h_addrtype == AF_INET)


It looks like gethostbyname(char * name) may return NULL, so it's a good idea to test for NULL before trying to access its contents.

If it is null then use WSAGetLastError() to query the error.
https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-gethostbyname

It also looks like the function is being deprecated, see the Note box near the top of the linked page. (I doubt deprecation is the issue, but it's something to keep in mind for future development).
Last edited on
As this topic is marked with a green tick, it looks like the OP has solved the problem without a comment as to how...


It also looks like the function is being deprecated, see the Note box near the top of the linked page.


It's been superseded by getaddrinfo() which will return both IP4 and IP6 addresses whereas gethostbyname() only works for IP4 addresses. But the OP wanted just IP4 so it's OK.

MS will never remove these 'deprecated' functions as there's far, far too much existing code using them!

Last edited on
Registered users can post here. Sign in or register to post.