InetAddress clientAddr = socket.getInetAddress();
clientAddr.isLoopbackAddress()
> I want to close a socket if the other side is not on the local
> machine, how can I do that?
>
> InetAddress.getHostname() is not "localhost" sometimes, if the
> client connects to "localhost". For example, sometimes getHostname()
> returns "127.0.0.1".
If it's a server doing this, then it's easier to simply prevent
non-local clients from connecting in the first place.
Just specify the localhost address when you create the ServerSocket.
Connection attempts on other interfaces will be refused by the
operating system, so you never have to deal with them in your
application.
/gordon

Signature
[ don't email me support questions or followups ]
g o r d o n + n e w s @ b a l d e r 1 3 . s e
Frank Fredstone - 11 Aug 2006 17:15 GMT
>> I want to close a socket if the other side is not on the local
>> machine, how can I do that?
[quoted text clipped - 10 lines]
> operating system, so you never have to deal with them in your
> application.
Thank you! It appears to do what you say, but I don't understand the
javadoc:
"The bindAddr argument can be used on a multi-homed host for a
ServerSocket that will only accept connect requests to one of its
addresses."
Is that saying the client must have a local address that is the same
as was given to the ServerSocket constructor on the server?
Gordon Beaton - 11 Aug 2006 17:49 GMT
> Thank you! It appears to do what you say, but I don't understand the
> javadoc:
[quoted text clipped - 5 lines]
> Is that saying the client must have a local address that is the same
> as was given to the ServerSocket constructor on the server?
The bind address specifies which of the server's interfaces the
connection must arrive on, not which address the client must have.
It's the address the client needs to *specify* in order to connect.
If you don't specify a bind address when you create the ServerSocket,
it "binds" to the wildcard address and consequently accepts
connections arriving on any of the host's (potentially multiple)
interfaces.
Note that after binding to 127.0.0.1, local clients can only connect
to 127.0.0.1 and will fail when they attempt to connect using the
"real" address of the host (even though they are connecting locally).
/gordon

Signature
[ don't email me support questions or followups ]
g o r d o n + n e w s @ b a l d e r 1 3 . s e
Hi there.
I would suggest you to delegate the test to a method, and throw an
exception if is the case.
if (!isLocalHost())
throw new NotLocalHostException();
protected boolean isLocalHost() {
boolean isLocal = false;
//whatever tests you can do in order to be sure that it is localhost
return isLocal;
}
OK?
Hope I Helped,
- Inácio Ferrarini
> I want to close a socket if the other side is not on the local
> machine, how can I do that?
[quoted text clipped - 16 lines]
> }
> }