• Support
  • Need to enable ethernet device in order to bind to 127.0.0.1?

I know it may be a very basic question, but I am able to bind to 127.0.0.1 using this code (see below), and it works(I get a message “============Binding succed!.” How come it is possible if my device does not have an eithernet device enabled or initialized? Should I do ethernet_init() ?

Thank you !

    int server;
    struct sockaddr_in serAdd;
    char *ip="127.0.0.1";

    server=socket(AF_INET,SOCK_STREAM,0);
    if(server<0)
    {
        LOG_ERR  ("**********Fail to create socket...");
        //return 0;
    }
    else
         LOG_ERR ("****************Binding...");

    serAdd.sin_family=AF_INET;
    //serAdd.sin_addr.s_addr=htonl(INADDR_ANY);
    serAdd.sin_addr.s_addr=htonl(INADDR_LOOPBACK);
    serAdd.sin_port=htons(6060);

    if(bind(server,(struct sockaddr *)&serAdd,sizeof(serAdd))==0)
 {
        LOG_ERR ("============Binding succed!...");
    }
    else
    {
        LOG_ERR ("=============Binding failed...");
        //return 0;
    }

Maybe because you’re using a loopback device?

Yes, I am using the loopback device, and I have additional settings enabled in prj.conf, and the loopback is there. However, this “socket” which is a result of the "server=socket(AF_INET,SOCK_STREAM,0); is not seen by other tasks. Every time I try to access socket in other threads, I get < err> net_sock: invalid access on sock 1 by thread 0×80000328, which is the same error when the socket is not correctly opened or does not exist.

prj.conf snippet
CONFIG_NET_IPV6=n
CONFIG_NET_IPV4=y
CONFIG_NET_MGMT=n
CONFIG_NET_TCP=y
CONFIG_NET_UDP=y
CONFIG_NET_LOOPBACK=y

Answering my own question here..
This error shows up if the socket is accidentally closed (which is what happened to me).
By the way, this code works in terms of creating a binding socket. Just be aware that some of the send() recv() calls may be blocking, so you have to make them non-blocking

k_sleep(K_MSEC(200));


    s_sock=socket(AF_INET,SOCK_STREAM,0);
    if(s_sock<0)
    {
       LOG_ERR  ("**********Fail to create socket...");
       //return 0;
    }
    else
        LOG_ERR ("****************Binding... s_sock %d", s_sock);

     k_sleep(K_SECONDS(2));

     s_addr.sin_family=AF_INET; // 1
     //serAdd.sin_addr.s_addr=htonl(INADDR_ANY);
     s_addr.sin_addr.s_addr=htonl(INADDR_LOOPBACK);
     s_addr.sin_port=htons(6060);

     if(bind(s_sock,(struct sockaddr *)&s_addr,sizeof(s_addr))==0)
     {
        LOG_ERR ("============Binding succed!...");
     }
     else
       {
          LOG_ERR ("=============Binding failed...");

       }
Terms and Conditions | Privacy Policy