This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

CCS/TM4C1294NCPDT: function DNSGetHostByName() solving wrong IP

Part Number: TM4C1294NCPDT


Tool/software: Code Composer Studio

I'm trying to use the DNSGetHostByName(), but when I try to solve "google.com" the function returns 0 (NO ERROR) and the IP saved in the HOSTENT structure is 28.246.0.32, which is not a correct google IP. I tried other domains, like "ti.com", "www.ti.com", "www.google.com", "yahoo.com", but the IP solved is always in format: *.246.0.32, changing only the first number. I also tried some different DNS server addresses, like 8.8.8.8, 8.8.4.4, 1.1.1.1, but they all gave me the same results.

Here is my code:

char dominio[DOMAIN_SIZE];
memset(dominio, 0, DOMAIN_SIZE);
strcpy(dominio, "google.com");

fdOpenSession((void *) Task_self());

int ret = -1;
char buff[DNS_BUFFER_SIZE];
memset(buff, 0, DNS_BUFFER_SIZE);

// Shows the actual DNS server address
IPN dns;
CfgGetImmediate(0, CFGTAG_SYSINFO, CFGITEM_DHCP_DOMAINNAMESERVER, 1, 4, (uint8_t *)&dns );
dns = ntohl(dns);
System_printf("DNS address: ");
System_printf("%d.%d.%d.%d\n",
                static_cast<uint8_t>((dns>>24)&0xFF),
                static_cast<uint8_t>((dns>>16)&0xFF),
                static_cast<uint8_t>((dns>>8)&0xFF),
                static_cast<uint8_t>(dns&0xFF));
System_flush();

ret = DNSGetHostByName(dominio, (void*)buff, DNS_BUFFER_SIZE);

if(ret == 0)
{
    HOSTENT *ht = (HOSTENT*)&buff[0];

    IPN IPAddr = ht->h_addr[0];

    IPAddr = ntohl(IPAddr);
    System_printf("IP solved: %d.%d.%d.%d\n",
                    (uint8_t)(IPAddr>>24)&0xFF,
                    (uint8_t)(IPAddr>>16)&0xFF,
                    (uint8_t)(IPAddr>>8)&0xFF,
                    (uint8_t)IPAddr&0xFF);
}
else
{
    System_printf("DNS error: %d\n", ret);
}

System_flush();

fdCloseSession((void *) Task_self());

Does anybody know what could be happening?

Thanks in advance,

Ronan

  • Hi,

      Where are you running the DNS code? If you are running in your office network then I will suggest, if possible, try in another network, e.g. home network? If you are getting the same result then I will forward your question to our NDK experts. I just wanted to make sure the problem is not network dependent. 

      Please also refer to the below two posts which might help. 

    https://e2e.ti.com/support/legacy_forums/embedded/tirtos/f/355/p/563235/2083624?tisearch=e2e-sitesearch&keymatch=could%20not%20resolve%20host%20name#2083624

    https://e2e.ti.com/support/microcontrollers/other/f/908/p/601702/2217180?tisearch=e2e-quicksearch&keymatch=getaddrinfo#2217180

  • Hi, Charles

    Thanks for replying me! I'm running my code in a home network and I'm using the same DNS server my laptop is using. I read the posts you sent, but they didin't help me.

  • Hi,

      Did you have a chance to run in a different network, e.g. your office network? Is there a firewall in your network? What if you disable the firewall and will it make a difference?

  • Hi,

    Unfortunately, I can't test the application in another network, but I have already disabled the firewall and it didn't make any difference.

    Regards,

    Ronan

  • Hi,

      It will be good if you can test in another network. In the meantime, I will forward your question to our NDK experts for advice.

  • Hi Ronan,

    If you have the necessary setup, it would be helpful if you could post a wireshark log of the DNS query and response.

    Regards,

    Dalton

  • Hi Dalton,

    The wireshark doesn't show any DNS packet coming from/to the device, only the DHCP request when I it's enabled.
    I forgot to mention that I'm initiating the NDK stack manually via C code. Is necessary to do anything special in the stack initialization process in order to use DNS?
    I'm attaching the stack initialization code below. I have already tested this code and the DHCP is working and I got a successful connection with a TCP server created by me.

    #define DHCP        // Comment to static IP
    
    #include <ti/ndk/inc/netmain.h>
    #include <ti/ndk/inc/os/oskern.h>
    #include <ti/sysbios/BIOS.h>
    #include <ti/sysbios/knl/Task.h>
    #include <ti/sysbios/knl/Clock.h>
    #include <ti/sysbios/utils/Load.h>
    #include <xdc/std.h>
    #include <xdc/runtime/System.h>
    
    #include <signal.h>
    #include <time.h>
    
    
    /* Socket file descriptor table */
    #define MAXSOCKETS 10
    uint32_t ti_ndk_socket_max_fd = MAXSOCKETS;
    void *ti_ndk_socket_fdtable[MAXSOCKETS];
    
    // NDK memory manager page size and number of pages [used by mmAlloc()]
    #define RAW_PAGE_SIZE 3072
    #define RAW_PAGE_COUNT 6
    
    const int ti_ndk_config_Global_rawPageSize  = RAW_PAGE_SIZE;
    const int ti_ndk_config_Global_rawPageCount = RAW_PAGE_COUNT;
    
    // P.I.T. (page information table)
    #ifdef __ti__
    #pragma DATA_SECTION(ti_ndk_config_Global_pit, ".bss:NDK_MMBUFFER");
    #pragma DATA_SECTION(ti_ndk_config_Global_pitBuffer, ".bss:NDK_MMBUFFER");
    PITENTRY ti_ndk_config_Global_pit[RAW_PAGE_COUNT];
    unsigned char ti_ndk_config_Global_pitBuffer[RAW_PAGE_SIZE * RAW_PAGE_COUNT];
    #elif defined (__IAR_SYSTEMS_ICC__)
    PITENTRY ti_ndk_config_Global_pit[RAW_PAGE_COUNT];
    unsigned char ti_ndk_config_Global_pitBuffer[RAW_PAGE_SIZE * RAW_PAGE_COUNT];
    #else
    PITENTRY ti_ndk_config_Global_pit[RAW_PAGE_COUNT]
            __attribute__ ((section(".bss:NDK_MMBUFFER")));
    unsigned char ti_ndk_config_Global_pitBuffer[RAW_PAGE_SIZE * RAW_PAGE_COUNT]
            __attribute__ ((section(".bss:NDK_MMBUFFER")));
    #endif
    
    /*
     * ======== ti_ndk_config_global_taskCreateHook ========
     * Automatically call fdOpenSession for dynamically created tasks.
     */
    Void ti_ndk_config_global_taskCreateHook(ti_sysbios_knl_Task_Handle h)
    {
    }
    
    /*
     * ======== ti_ndk_config_global_taskExitHook ========
     * Automatically call fdCloseSession for dynamically created tasks.
     */
    Void ti_ndk_config_global_taskExitHook(ti_sysbios_knl_Task_Handle h)
    {
    }
    
    
    // Memory bucket sizes
    #define SMALLEST 48
    #define LARGEST (RAW_PAGE_SIZE)
    
    const int ti_ndk_config_Global_smallest = SMALLEST;
    const int ti_ndk_config_Global_largest  = LARGEST;
    
    // Memory Slot Tracking
    uint32_t ti_ndk_config_Global_Id2Size[] = {SMALLEST, 96, 128, 256, 512, 1536, LARGEST};
    
    /*
     *  Number of buffers in PBM packet buffer free pool
     *
     *  The number of buffers in the free pool can have a significant effect
     *  on performance, especially in UDP packet loss. Increasing this number
     *  will increase the size of the static packet pool use for both sending
     *  and receiving packets.
     */
    #define PKT_NUM_FRAMEBUF 10
    
    // Size of Ethernet frame buffer
    #define PKT_SIZE_FRAMEBUF   1536
    
    const int ti_ndk_config_Global_numFrameBuf = PKT_NUM_FRAMEBUF;
    const int ti_ndk_config_Global_sizeFrameBuf = PKT_SIZE_FRAMEBUF;
    
    /*
     *  Data space for packet buffers
     *
     *  Buffers are aligned on 4 byte boundaries to satisfy the EMAC's DMA
     */
    unsigned char ti_ndk_config_Global_pBufMem[PKT_NUM_FRAMEBUF * PKT_SIZE_FRAMEBUF]
            __attribute__ ((aligned(4)));
    unsigned char ti_ndk_config_Global_pHdrMem[PKT_NUM_FRAMEBUF * sizeof(PBM_Pkt)]
            __attribute__ ((aligned(4)));
    
    
    
    /* Our NETCTRL callback functions */
    static void networkOpen();
    static void networkClose();
    static void networkIPAddr(uint32_t IPAddr, uint32_t IfIdx, uint32_t fAdd);
    static char *hostName = "tisoc";
    
    extern void llTimerTick();
    
    const char *LocalIPAddr = "192.168.1.12";
    const char *LocalIPMask = "255.255.255.0";
    const char *GatewayIP   = "192.168.1.1";
    const char *DNSAddr     = "8.8.8.8";
    const char *DomainName  = "demo.net";
    
    /*
     *  ======== networkOpen ========
     *  This function is called after the configuration has booted
     */
    static void networkOpen()
    {
        System_printf("Network open hook!\n");
        System_flush();
    }
    
    /*
     *  ======== networkClose ========
     *  This function is called when the network is shutting down,
     *  or when it no longer has any IP addresses assigned to it.
     */
    static void networkClose()
    {
        System_printf("Network close hook!\n");
        System_flush();
    }
    
    /*
     *  ======== networkIPAddr ========
     *  This function is called whenever an IP address binding is
     *  added or removed from the system.
     */
    static void networkIPAddr(uint32_t IPAddr, uint32_t IfIdx, uint32_t fAdd)
    {
        uint32_t IPTmp;
    
        if (fAdd) {
            System_printf("Network Added: ");
        }
        else {
            System_printf("Network Removed: ");
        }
    
        // print the IP address that was added/removed
        IPTmp = ntohl(IPAddr);
        System_printf("If-%d:%d.%d.%d.%d\n", IfIdx,
                      (uint8_t)(IPTmp>>24)&0xFF, (uint8_t)(IPTmp>>16)&0xFF,
                      (uint8_t)(IPTmp>>8)&0xFF, (uint8_t)IPTmp&0xFF);
        System_flush();
    }
    
    /*
     *  ======== serviceReport ========
     *  Function for reporting service status updates.
     */
    static char *taskName[] = {"Telnet", "HTTP", "NAT", "DHCPS", "DHCPC", "DNS"};
    static char *reportStr[] = {"", "Running", "Updated", "Complete", "Fault"};
    static char *statusStr[] = {"Disabled", "Waiting", "IPTerm", "Failed","Enabled"};
    static void serviceReport(uint32_t item, uint32_t status, uint32_t report, void *h)
    {
        System_printf("Service Status: %-9s: %-9s: %-9s: %03d\n",
                      taskName[item - 1], statusStr[status], reportStr[report / 256],
                      report & 0xFF);
        System_flush();
    }
    
    /*
     *  ======== initTcp ========
     *  Configure the stack's TCP settings
     */
    static void initTcp(void *hCfg)
    {
        int transmitBufSize = 1024;
        int receiveBufSize = 1024;
        int receiveBufLimit = 2048;
    
        CfgAddEntry(hCfg, CFGTAG_IP, CFGITEM_IP_SOCKTCPTXBUF, CFG_ADDMODE_UNIQUE,
                sizeof(uint32_t), (unsigned char *)&transmitBufSize, NULL);
        CfgAddEntry(hCfg, CFGTAG_IP, CFGITEM_IP_SOCKTCPRXBUF, CFG_ADDMODE_UNIQUE,
                sizeof(uint32_t), (unsigned char *)&receiveBufSize, NULL);
        CfgAddEntry(hCfg, CFGTAG_IP, CFGITEM_IP_SOCKTCPRXLIMIT, CFG_ADDMODE_UNIQUE,
                sizeof(uint32_t), (unsigned char *)&receiveBufLimit, NULL);
    }
    
    /*
     *  ======== initIp ========
     *  Configure the stack's IP settings
     */
    static void initIp(void *hCfg)
    {
    #ifdef DHCP
        // DHCP
        CI_SERVICE_DHCPC dhcpc;
        unsigned char DHCP_OPTIONS[] = { DHCPOPT_SUBNET_MASK };
    
        // hostname
        CfgAddEntry(hCfg, CFGTAG_SYSINFO, CFGITEM_DHCP_HOSTNAME, 0,
                    strlen(hostName), (unsigned char *)hostName, NULL);
    
        // Use DHCP to get IP in interface 1
        memset(&dhcpc, 0, sizeof(dhcpc));
        dhcpc.cisargs.Mode = CIS_FLG_IFIDXVALID;
        dhcpc.cisargs.IfIdx = 1;
        dhcpc.cisargs.pCbSrv = &serviceReport;
        dhcpc.param.pOptions = DHCP_OPTIONS;
        dhcpc.param.len = 1;
        CfgAddEntry(hCfg, CFGTAG_SERVICE, CFGITEM_SERVICE_DHCPCLIENT, 0,
                  sizeof(dhcpc), (unsigned char *)&dhcpc, NULL);
    
    #else
        // static IP
        CI_IPNET NA;
        CI_ROUTE RT;
    
        // hostname
        CfgAddEntry(hCfg, CFGTAG_SYSINFO, CFGITEM_DHCP_HOSTNAME, 0,
                    strlen(hostName), (unsigned char *)hostName, NULL);
    
        // Ip and mask
        bzero(&NA, sizeof(NA));
        NA.IPAddr  = inet_addr(LocalIPAddr);
        NA.IPMask  = inet_addr(LocalIPMask);
        strcpy(NA.Domain, DomainName);
        NA.NetType = CFG_NETTYPE_VIRTUAL;
        CfgAddEntry(hCfg, CFGTAG_IPNET, 1, 0, sizeof(CI_IPNET), (UINT8 *)&NA, 0);
    
        // Gateway
        bzero(&RT, sizeof(RT));
        RT.IPDestAddr = 0;
        RT.IPDestMask = 0;
        RT.IPGateAddr = inet_addr(GatewayIP);
        CfgAddEntry(hCfg, CFGTAG_ROUTE, 0, 0, sizeof(CI_ROUTE), (UINT8 *)&RT, 0);
    
    
        // DNS
        IPN IPTmp;
        IPTmp = inet_addr(DNSAddr);
        CfgAddEntry( hCfg, CFGTAG_SYSINFO, CFGITEM_DHCP_DOMAINNAMESERVER, 0, sizeof(IPTmp),
                     (unsigned char *)&IPTmp, 0 );
    #endif
    }
    
    /*
     *  ======== initUdp ========
     *  Configure the stack's UDP settings
     */
    void initUdp(void *hCfg)
    {
        int receiveBufSize = 2048;
    
        CfgAddEntry(hCfg, CFGTAG_IP, CFGITEM_IP_SOCKUDPRXLIMIT, CFG_ADDMODE_UNIQUE,
                sizeof(uint32_t), (unsigned char *)&receiveBufSize, NULL);
    }
    
    /*
     *  ======== ndkStackThread ========
     *  NDK stack's main thread function
     */
    void NDKManagerTaskFxn()
    {
        void *hCfg;
        int rc;
        Clock_Params clockParams;
        Clock_Handle ndkClockHandle;
    
        // Create the NDK heart beat
        Clock_Params_init(&clockParams);
        clockParams.startFlag = TRUE;
        clockParams.period = ((100*1000)/Clock_tickPeriod);
        ndkClockHandle = Clock_create((Clock_FuncPtr)llTimerTick, clockParams.period,
                                      &clockParams, NULL);
        if (ndkClockHandle == NULL) {
            System_printf("Problema ao criar relogio\n");
            System_flush();
            return;
        }
    
        rc = NC_SystemOpen(NC_PRIORITY_LOW, NC_OPMODE_INTERRUPT);
        if (rc) {
            System_printf("ndkStackThread: NC_SystemOpen Failed\n");
            System_flush();
            return;
        }
    
        // create and build the system configuration from scratch.
        hCfg = CfgNew();
        if (!hCfg) {
            System_printf("ndkStackThread: Unable to create configuration\n");
            System_flush();
            goto main_exit;
        }
    
        // IP, TCP, and UDP config
        initIp(hCfg);
        initTcp(hCfg);
        initUdp(hCfg);
    
        // config low priority tasks stack size
        rc = 2048;
        CfgAddEntry(hCfg, CFGTAG_OS, CFGITEM_OS_TASKSTKLOW, CFG_ADDMODE_UNIQUE,
                sizeof(uint32_t), (unsigned char *)&rc, NULL);
    
        // config norm priority tasks stack size
        rc = 2048;
        CfgAddEntry(hCfg, CFGTAG_OS, CFGITEM_OS_TASKSTKNORM, CFG_ADDMODE_UNIQUE,
                sizeof(uint32_t), (unsigned char *)&rc, NULL);
    
        // config high priority tasks stack size
        rc = 2048;
        CfgAddEntry(hCfg, CFGTAG_OS, CFGITEM_OS_TASKSTKHIGH, CFG_ADDMODE_UNIQUE,
                sizeof(uint32_t), (unsigned char *)&rc, NULL);
    
        // Seta handle de configuração hCfg como o default
        CfgSetDefault(hCfg);
    
        do
        {
            rc = NC_NetStart(hCfg, networkOpen, networkClose, networkIPAddr);
        } while(rc > 0);
    
        System_printf("Saiu de NC_NetStart\n");
        System_flush();
    
        /* Shut down the stack */
        CfgFree(hCfg);
    
    main_exit:
        NC_SystemClose();
    
        Clock_delete(&ndkClockHandle);
    
        System_printf("ndkStackThread: exiting ...\n");
        System_flush();
    }
    

    Thanks in advance,

    Ronan

  • Hi Ronan,

    You wouldn't see any DNS traffic from your board unless you have a router/switch capable of port mirroring as the DNS traffic never goes through your computer running wireshark. Your startup function also looks good to me. 

    Could you show me the NDK libraries you are linking? The DNS functions can cause odd failures if an IPv6 library is used without IPv6 code. Also, are you throwing a compiler define for _INCLUDE_IPv6_CODE?

    It also looks like you are using NDK v2.x, so you could see if you get the correct results when using the getaddrinfo() function.

    Regards,

    Dalton

  • Hi Dalton,

    Thanks for replying me! These are the libraries that I'm linking:

    Is there any problem with the libraries? I tried to remove the stk6 from the list, but when if I do that I get the error unresolved symbol IPv6Init, first referenced in .../netctrl.aem4f.

    I'm not defining the _INCLUDE_IPv6_CODE in the compiler options, neither in any part of my code.

    About the getaddrinfo(), I didn't know this function. I'm going to read about it now and try to use it.

    Thanks in advance,

    Ronan

  • Hello Ronan,

    I see the problem now. You're on the right track with removing the stk6 library but there are a few more things to do. First some background. The NDK libraries are split between ipv4 and ipv6 libraries (ipv6 libraries were built with _INCLUDE_IPv6_CODE defined). It looks like you aren't doing any ipv6 operations, so you should just use the ipv4 versions. Here is what your library list will look like afterwards:

    ti/ndk/hal/timer_bios/lib/hal_timer.aem4f
    ti/ndk/hal/eth_stub/lib/hal_eth_stub.aem4f
    ti/ndk/tools/hdlc/lib/hdlc.aem4f
    ti/ndk/netctrl/lib/netctrl_ipv4.aem4f 
    ti/ndk/nettools/lib/nettool_ipv4.aem4f
    ti/ndk/hal/ser_stub/lib/hal_ser_stub.aem4f
    ti/ndk/hal/userled_stub/lib/hal_userled_stub.aem4f
    ti/ndk/stack/lib/stk.aem4f
    ti/ndk/os/lib/os.aem4f

    The libraries in bold are the ones using the ipv4 versions. Your linker error was happening because you only changed the stk library to the IPv4 version (also you only ever need one of the stk libraries included). Now why does any of this matter for DNS operations? Well the HOSTENT struct has the following code in its definition:

    #ifndef _INCLUDE_IPv6_CODE
    
        /**
         * @brief   List of upto NDK_DNS_MAXIPADDR IPv4 addresses (Network format) that map
         * to the given hostname.
         */
         uint32_t h_addr[NDK_DNS_MAXIPADDR];
    
    #else
    
        /**
         * @brief   List of upto NDK_DNS_MAXIPADDR IPv4/IPv6 addresses that map to given hostname.
         */
         char*   h_addr_list[NDK_DNS_MAXIPADDR];
    
    #endif
    

    So using ipv6 libraries in an app that doesn't throw _INCLUDE_IPv6_CODE will cause the wrong address list to be accessed.

    That is most likely the problem you are running into. Try changing your libraries to what I listed above and see if that works for you. 

    Regards,

    Dalton

  • Hi Dalton,

    This solved my problem! Thank you so much for helping me!

    The NDK docs don't specify how to link the ndk libraries manually, so I tried to discover by myself based on the unresolved symbols returned by the linker. Now, I'm sure I'm using the correct libraries! :D