Skip to content
Advertisement

Who can send to a socket bound to INADDR_LOOPBACK?

I’m somewhat new to socket programming, and am confused about the concept of binding a socket to the address INADDR_LOOPBACK, or 127.0.0.1.

If I’m writing server code to listen for messages on a specific port, and I bind a socket to an address as in the following code exerpt…

int sd = socket( PF_INET, SOCK_DGRAM, 0 );
sockaddr_in si;
si.sin_family = AF_INET;
si.sin_addr.s_addr = inet_addr( "127.0.0.1" );
si.sin_port = htons( 9090 );
bind( sd, (sockaddr*)&si, sizeof si )

…my question is: who is able to send to this socket?

I know that other processes running on the same PC as the server process can reach the above socket, by doing a sendto() with a dest_addr argument specifying 127.0.0.1.

But can clients on other PCs on the same network also send to that socket if they know the server’s “actual” address? What I mean is: if I run ifconfig on a Linux PC, I’ll see an inet address, e.g. 10.138.19.27. Does this mean a client process on a different PC than the server, but on the same network, can send to the server’s socket – which was bound to 127.0.0.1 – if the client specifies an address of 10.138.19.27?

Advertisement

Answer

Only connections to the loopback adapter (127.0.0.1), and those can only originate from the same machine as the listener since the other interfaces intentionally avoid rounding to that one.


When you don’t bind or when you bind to INADDR_ANY (0.0.0.0), you accept connections from all interfaces.

Window 1                                    Window 2
------------------------------------------  ------------------------------------------
                                            $ nc -l 5678
$ echo test-ip | nc 69.163.162.155 5678     test-ip

$ echo $?
0
                                            $ nc -l 5678
$ echo test-localhost | nc localhost 5678   test-localhost

$ echo $?
0

When you bind to an IP address, you only accept connections directed to that IP address.

Window 1                                    Window 2
------------------------------------------  ------------------------------------------
                                            $ nc -l 69.163.162.155 5678
$ echo test-localhost | nc localhost 5678

$ echo $?
1

$ echo test-ip | nc 69.163.162.155 5678     test-ip

$ echo $?
0

The same goes for addresses in 127.x.x.x.

Window 1                                    Window 2
------------------------------------------  ------------------------------------------
                                            $ nc -l localhost 5678
$ echo test-ip | nc 69.163.162.155 5678

$ echo $?
1

$ echo test-localhost | nc localhost 5678   test-localhost

$ echo $?
0

The special thing about 127.x.x.x is that only your own machine can reach 127.x.x.x addresses.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement