简体   繁体   中英

"Socket.RemoteHost" in some networks returns IP instead of ComputerName - Delphi

I'm using "OnClientConnect" of TServerSocket to identify when a client connects to chat, and save the ComputerName of the client in a listbox to manage sending messages between clients.

The code is like this:

    procedure TfrmAnaForm.ServerSocket1ClientConnect(Sender: TObject; Socket: TCustomWinSocket);
    var 
       ComputerName: string;
    begin    
        frmChatMain.lstChatUsers.Items.Add(Socket.RemoteHost);    
    end;

The problem is that Normally "Socket.RemoteHost" returns "ComputerName" of the client, but in some.networks, the code "Socket.RemoteHost" returns IP of client instead of "ComputerName" of client.

The RemoteHost property retrieves the client's IP address from the socket, and then performs a reverse DNS lookup of the client's hostname for that IP. If that lookup fails, RemoteHost returns a blank string, not the IP address. The only way RemoteHost can return an IP address is if that is what the DNS system actually reported.

You should not be using the RemoteHost to uniquely identify clients, because 1) it is not guaranteed to even give you a value, and 2) it is not guaranteed to be unique, such as if multiple remote clients are connecting from the same computer.network. At the very least, you must use RemoteIP + RemotePort instead of RemoteHost to identify individual connections. Though, you really should be using the TCustomWinSocket object itself to identify unique connections. Even better, require clients to login to your server with a unique ID, which you can then store inside the TCustomWinSocket.Data property so it follows the connection it belongs to.

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