Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why bind a socket to an address?

Tags:

Before 'listen'ing on a socket I must first bind it to an address. Why? It seems to me that I shouldn't have to pick and should just listen to that port on all addresses. Even if I bind to 127.0.0.1 though, it seems I can still connect to that socket from a remote machine. What does binding to an address really do?

like image 777
Pace Avatar asked Sep 26 '11 14:09

Pace


People also ask

Why do you need to bind a socket?

The bind() method is used when a socket needs to be made a server socket. As server programs listen on published ports, it is required that a port and the IP address to be assigned explicitly to a server socket. For client programs, it is not required to bind the socket explicitly to a port.

What does it mean to bind a socket to an address?

When a socket has both an IP address and a port number it is said to be 'bound to a port', or 'bound to an address'. A bound socket can receive data because it has a complete address. The process of allocating a port number to a socket is called 'binding'.

What does binding an address do?

Compile Time Address Binding The address binding assigns a logical address to the beginning of the memory segment to store the object code. Memory allocation is a long-term process and may only be modified by recompiling the program.

What is the need for a socket addressing?

This is the internet domain, denoted by AF_INET in C. Many of the socket calls require you to define the domain as one of their parameters. A socket address is defined by the IP address of the socket and the port number allocated to the socket.


1 Answers

Binding to an address defines exactly which interface should have that server port open. binding to 0.0.0.0 is a special case when you want to listen to all IP addresses know to the interface. Binding specifically to 127.0.0.1 should make the server port visible only to code that can connect to the localhost (e.g. local processes).

like image 136
long404 Avatar answered Oct 30 '22 17:10

long404