简体   繁体   中英

Socket programming client name

Is there any way to get client name at the server side before "accepting" the connection? Using java.

I am new to java.

thanks in advance..

Is there any way to get client name at the server side before "accepting" the connection?

No - you must accept the connection first. Then you may read the host's name and choose the next course of action.

Socket client = server.accept();
String hostName = client.getInetAddress().getHostName();

The client name (the client hostname) is avalaible only from the Socket client, so you need to accept it first and then then to react accordingly.

private static final String ALLOWED_NAME = "my.hostname.com";

....

Socket client = server.accept();
String hostName = client.getInetAddress().getCanonicalHostName();

if(hostName.equalsIgnoreCase(ALLOWED_NAME)
{
   // DO NOTHING
}
else 
{
   client.close();
}

Reference:

Please be sure to get the difference between getCanonicalHostname () and getHostname() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM