l4x3
l4x3

Reputation: 3

C++ socket programming bind function

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;
    }

Upvotes: 0

Views: 924

Answers (1)

rustyx
rustyx

Reputation: 85531

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)).

Upvotes: 2

Related Questions