Please read the comment by EJP and rethink your requirements first.
Regardless of why you would want this, you will need to take a couple of steps:
- Find the context (LDAP container) where your users are. AD default is
cn=Users,dc=your,dc=domain,dc=com
. - Identify the LDAP attribute containing the IP Addresses (let's say
networkAddress
for now) - Retrieve the IP Address from the HTTP request (let's say
String userAddress
) - Perform the query for the (user) object using the filter
(&(objectClass=inetOrgPerson)(networkAddress=userAddress))
Your Java code would look like this (assuming you have a live LdapConnection
object as you mentioned):
public void getUserByIp( LdapContext ctx, String userAddress )
{
// Replace with your context and domain name
String userContext = "cn=Users,dc=your,dc=domain,dc=com";
String filter = "(&(objectClass=inetOrgPerson)(networkAddress="+userAddress+"))";
// You are trying to find a single user, so set the controls to return only on instance
SearchControls contr = new SearchControls();
contr.setCountLimit( 1L );
try
{
NamingEnumeration<SearchResult> results = ctx.search( userContext, filter, contr );
while ( results.hasMore() )
{
// User found
SearchResult user = results.next();
} else {
// No user found
}
} catch ( NamingException e ) {
// If there is more than one result, this error will be thrown from the while loop
}
}