覚えたら書く

IT関係のデベロッパとして日々覚えたことを書き残したいです。twitter: @yyoshikaw

Spring Boot - アクセス元のIPアドレスをIPv4形式で取得したい

Spring BootでWebアプリを構築する際に、
仮に以下のようなコードがあった場合、WebAuthenticationDetails#getRemoteAddressでアクセス元のIPアドレスを取得することができます。

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;


@Slf4j
@Component
public class AppAuthenticationEventListener {

    @EventListener
    public void onApplicationEvent(AuthenticationSuccessEvent e) {
        UserDetails user = (UserDetails) e.getAuthentication().getPrincipal();

        Authentication auth = e.getAuthentication();
        WebAuthenticationDetails details = (WebAuthenticationDetails) auth.getDetails();

        String ipAddress = details.getRemoteAddress();

        log.info("login success : {} from {}", user, ipAddress);
    }
}

この際に、IPv6が有効な環境では取得するIPアドレスもIPv6形式になります。
場合によっては、IPv6形式ではなくIPv4形式で取得したい場合もあると思います。

その場合はapplication.ymlのserver.addressに、(アプリがListenする)IPアドレスをIPv4形式で指定します。

server:
  address: 127.0.0.1


こうすることでgetRemoteAddressメソッドで返されるIPアドレスもIPv4形式となります