$theTitle=wp_title(" - ", false); if($theTitle != "") { ?>
About Virtualization, VDI, SBC, Application Compatibility and anything else I feel like
When a client is connected to a Terminal Server Session you can use the Terminal Server API to retrieve the client’s local IP address.
Start by enumerating all sessions with WtsEnumerateSessions and then for each session get the ClientAddress with a call to WTSQuerySessionInformation with the WTSClientAddress parameter. Sound simple, no?
WTSQuerySessionInformation returns a pointer to a WTS_CLIENT_ADDRESS structure. You need to know that the IP address is located at on offset of 2 bytes in the Address member of WTS_CLIENT_ADDRESS.
So here’s a sample:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | uses JwaWinType, JwaWtsApi32, JwaWinsock2, ExtCtrls; type PWtsSessionInfoAArray = ^TWtsSessionInfoAArray; TWtsSessionInfoAArray = array[0..ANYSIZE_ARRAY-1] of WTS_SESSION_INFOA; var hServer: THandle; SessionInfoPtr: PWtsSessionInfoAArray; pCount: Cardinal; ClientAddressPtr: PWtsClientAddress; dwBytesReturned: Cardinal; IPStr: String; i: integer; begin if WtsEnumerateSessions(WTS_CURRENT_SERVER, 0, 1, PWTS_SESSION_INFO(SessionInfoPtr), pCount) then begin for i := 0 to pCount - 1 do begin WTSQuerySessionInformation(WTS_CURRENT_SERVER, SessionInfoPtr^[i].SessionId, WTSClientAddress, Pointer(ClientAddressPtr), dwBytesReturned); case ClientAddressPtr^.AddressFamily of AF_INET: IPStr:= Format('%d.%d.%d.%d', [ClientAddressPtr^.Address[2], ClientAddressPtr^.Address[3], ClientAddressPtr^.Address[4], ClientAddressPtr^.Address[5]]); AF_INET6: IPStr:= 'IPv6 address not yet supported'; AF_IPX: IPStr:= 'IPX is not supported'; AF_NETBIOS: IPStr:= 'NETBIOS is not supported'; AF_UNSPEC: IPStr:= 'Unspecified (console and listener session have no address)'; end; WTSfreeMemory(ClientAddressPtr); end; end; // Don't close the handle if it's WTS_CURRENT_SERVER WtsFreeMemory(SessionInfoPtr); end; |
Screenshot:
ClientIP.zip (3686 downloads)
8 Responses for "How to get Client IP Address?"
The code was somehow messed up when I pasted it in WordPress. It should be ok now. I also added a little demo app with source.
Thanks! This works very nicely
Where are units, JwaWinType, JwaWtsApi32, JwaWinsock2? Could not find it anywhere 🙁
search with google.
@Bora: Lanis is right, Google would have found you the answer: http://blog.delphi-jedi.net/jedi-api-headers/
Unfortunately I got always 73.0.0.0 or 0.0.0.0 when I connect to PS via TS gateway, if I connect directly to PC I got the proper client IP.
Is there any solution to get client IP (via TS gateway) or TS gateway does hide it?
Thanks a lot!
But how to get the local IP within a session?
I need only the ip from my own session.
@JoeE: check out my answer to this question on stackoverflow: http://stackoverflow.com/questions/576538/delphi-how-to-get-all-local-ips/1116526#1116526
Leave a reply