使用IP地址属性的LDAP查询

时间:2014-03-02 17:13:18

标签: java active-directory ldap

我正在寻找一种使用用户的IP地址查询LDAP的方法。

当有人使用浏览器时,浏览器会发送其IP地址。 我想使用该IP地址查询LDAP以查找该IP地址所属的用户名。

我已经设法使用Java中的LDAP建立AD连接。

1 个答案:

答案 0 :(得分:1)

请阅读 EJP 的评论,并首先重新考虑您的要求。

无论为什么你都想要这个,你需要采取以下几个步骤:

  • 查找用户所在的上下文(LDAP容器)。 AD默认值为cn=Users,dc=your,dc=domain,dc=com
  • 识别包含IP地址的LDAP属性(暂时说networkAddress
  • 从HTTP请求中检索IP地址(假设为String userAddress
  • 使用过滤器(&(objectClass=inetOrgPerson)(networkAddress=userAddress))
  • 执行(用户)对象的查询

您的Java代码看起来像这样(假设您有一个如您所提到的实时LdapConnection对象):

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
  }
}
相关问题