0

Im learning socket progrmming in c++ and i don't understand why this function binds the socket to 'localhost'. For example, in python you have to specify the host like this:

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('localhost', 1234))

If I'm not wrong, this c ++ function is binding the socket in the same way. But, why it is localhost?

int _bind(int port)
    {

        bzero((char *)&serv_addr, sizeof(serv_addr));

        serv_addr.sin_family = AF_INET;
        serv_addr.sin_addr.s_addr = INADDR_ANY;
        serv_addr.sin_port = htons(port);

        if (bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
        {
            error("can't bind socket");
            return -1;
        }
        return 1;
    }
l4x3
  • 3
  • 3
  • https://stackoverflow.com/questions/16508685/understanding-inaddr-any-for-socket-programming/16510000 – Devolus Apr 06 '21 at 12:13
  • 1
    Does this answer your question? [Understanding INADDR\_ANY for socket programming](https://stackoverflow.com/questions/16508685/understanding-inaddr-any-for-socket-programming) – Hasturkun Apr 06 '21 at 12:30
  • This function does not bind to localhost, which is just perfect. You should not bind to localhost either in C++ or Python, unless you want to start a local-only service invisible from the outside. Just in case, if you for some reason do want to bind to localhost, use `INADDR_LOOPBACK` instead of `INADDR_ANY` (and you have to use `htonl(address)`). – n. m. could be an AI Apr 06 '21 at 12:52

1 Answers1

1

Binding to "localhost" or INADDR_LOOPBACK binds to the loopback interface only. It will allow connecting locally using e.g. 127.0.0.1, but not from the network.

Binding to INADDR_ANY binds to all interfaces. It will allow connecting to this machine from another machine via the network using its network IP (e.g. 192.168.1.2).

The Python equivalent of binding to INADDR_ANY is sock.bind(('0.0.0.0', 1234)).

rustyx
  • 80,671
  • 25
  • 200
  • 267