Arm Mbed OS support forum

Issue with ai_protocol in int mbedtls_net_connect()?

Ran into the issue with ai_protocol value in mbedtls_net_connect() function. Used as is on IPv4 enabled platform the call to mbedtls_net_connect() returns error -0x066. That is caused by the line

hints.ai_protocol = proto == MBEDTLS_NET_PROTO_UDP ? IPPROTO_UDP : IPPROTO_TCP;

which when function is called with MBEDTLS_NET_PROTO_TCP for “proto” sets the hints.ai_protocol to IPPROTO_TCP which is defined as 6.

Setting hints.ai_protocol manually to 0 makes everything work fine. I see the same done in Google’s GCP IoT library for example, where the mbedtls_net_connect() is reimplemented and the hints.ai_protocol is set to 0 as well.

Is this a bug in the code? I didn’t check if this works on Linux/Win or Cygwin as we are not using mbedTLS on those platforms.

mbedTLS version we are using is:

mbedTLS version: mbed TLS 2.16.6 branch released 2020-04-14

The code in question:
/*

  • Initiate a TCP connection with host:port and the given protocol
    */
    int mbedtls_net_connect( mbedtls_net_context *ctx, const char *host,
    const char *port, int proto )
    {
    int ret;
    struct addrinfo hints, *addr_list, *cur;

    if( ( ret = net_prepare() ) != 0 )
    return( ret );

    /* Do name resolution with both IPv6 and IPv4 */
    memset( &hints, 0, sizeof( hints ) );
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = proto == MBEDTLS_NET_PROTO_UDP ? SOCK_DGRAM : SOCK_STREAM;
    hints.ai_protocol = proto == MBEDTLS_NET_PROTO_UDP ? IPPROTO_UDP : IPPROTO_TCP;

    if( getaddrinfo( host, port, &hints, &addr_list ) != 0 )
    return( MBEDTLS_ERR_NET_UNKNOWN_HOST );

    /* Try the sockaddrs until a connection succeeds */
    ret = MBEDTLS_ERR_NET_UNKNOWN_HOST;
    for( cur = addr_list; cur != NULL; cur = cur->ai_next )
    {
    ctx->fd = (int) socket( cur->ai_family, cur->ai_socktype,
    cur->ai_protocol );
    if( ctx->fd < 0 )
    {
    ret = MBEDTLS_ERR_NET_SOCKET_FAILED;
    continue;
    }