title: How do I have a socket accept connections only from the localhost (in Java)?
body: <p>I have a java app (not running in any application container) which listens on a ServerSocket for connections.  I would like it to only accept connections which come from localhost.  Currently, after a connection is accepted, it checks the peer IP and rejects it if it is not the loopback address, but I know that peer IP addresses can be spoofed.  So, if possible, I'd prefer to bind to a socket that only listens on the loopback interface; is this possible?</p>
  <p>I've tried a few different things (such as specifying &quot;127.0.0.1&quot; as the local address when calling bind()) with no luck.</p>
  <hr />
  <p><strong>Update:</strong></p>
  <p>I'm embarrassed to admit that this was all my mistake.  Our application listens on two different ports, and I was binding one to the loopback interface but testing against the other.  When I actually try to telnet to the correct port, everything works fine (i.e., binding to &quot;127.0.0.1&quot; does exactly what it's supposed to).</p>
  <p>As for spoofing the loopback address, you guys are right.  I shouldn't have made it sound like the primary concern.  Really, the desired behavior is to only take local connections, and binding to only the local interface is a more direct way of achieving that than accepting all connections and then closing non-local ones.</p>