Pregunta

I am reading about socket programming and got to know that ip is assigned to socket with bind() call before connection to server.Is my thinking of binding address means to bind any ip address correct.

¿Fue útil?

Solución

bind() defines a relationship between the socket you created and the addresses that are available on your host. For example you can bind a socket on all addresses or on a specific IP which has been configured on a network adapter by the host's operating system.

Here is an example how to bind a socket to all available addresses on the host that runs this code:

struct sockaddr_in name;

name.sin_family = AF_INET;
name.sin_port = htons (port);
name.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind (socket, (struct sockaddr *) &name, sizeof (name)) < 0) {
    perror ("bind");
    exit (-1);
}

For a server application, users sometimes like to restrict the socket to be bound only to a certain address for security reasons or just to map the services where they want them to be available. This is why most servers allow to configure bind addresses for the users easily with the application's configuration file.

Licenciado bajo: CC-BY-SA con atribución
scroll top