Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

The private IP address of my machine is 192.168.44.182. If I started a process using

nc -l localhost 20000

Then this process won't handle requests sent to 192.168.44.182.

Since the process listening to localhost:20000 does run on the physical machine with LAN IP being 192.168.44.182, I'm trying to know how the process ignores the requests to 192.168.44.182.

Is it true that these requests are ignored by the process, or such requests are not delivered to the network interface of 127.0.0.1 at all? Is this a network-layer mechanism, or link-layer mechanism?

share|improve this question
1  
The process doesn't ignore those requests - the process won't even notice the request. –  Bonsi Scott Dec 3 '12 at 19:09
add comment

2 Answers

up vote 3 down vote accepted

When you set up a listening socket, you can pick which local address it is bound to. This is done with the bind(2) system call. (You can also choose to bind it to 0.0.0.0, which means listen on all local addresses).

You told netcat to listen on localhost. So it called bind(2) with 127.0.0.1 (or similar) as the socket address. So the kernel bound the listening socket to only that address.

When a connection request came in to 192.168.44.182:20000 the kernel looked at the list of listening sockets, and found none. So the kernel refused the connection.

When a request comes in to 127.0.0.1:20000, the kernel will find the listening socket, and the accept(2) syscall will tell netcat about it.

To have netcat listen on all interfaces, omit the host: nc -l -p 20000 or alternatively specify 0.0.0.0: nc -l 0.0.0.0 -p 20000. You can also specify the specific IP address you want it to listen on as well (192.168.44.182), but then of course nc localhost 20000 will be rejected.

(Binding to localhost is often done when you only want to allow connections from the same machine, e.g., for security reasons.)

share|improve this answer
add comment

Every socket has 2 characteristics associated with it. Address and port. Socket listening on every interface actually listens on an address INADDR_ANY, which is 0.0.0.0, so since you tell the socket it's listening on 127.0.0.1 it will ignore all requests to other addresses of the machine.

share|improve this answer
    
On most unixes, you can also have an interface bound to the socket. But very few programs support the option, as it is not portable, especially on non-unix systems. –  BatchyX Dec 3 '12 at 20:09
    
@BatchyX True but that is a topic advanced beyond the scope of this question. –  Karlson Dec 3 '12 at 20:11
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.