Question

I am looking for a way to query LDAP using the IP Address of a user.

When someone is using a browser, the browser sends its IP Address along. I want to use that IP Address to query LDAP to find the user name to which that IP Address belongs to.

I have already managed to make a connection to AD using LDAP in Java.

No correct solution

OTHER TIPS

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
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top