JAVA

[JAVA] IP 정보 가져오기

배고파요 2022. 12. 6. 14:26
728x90

처음 시도한 것.::

- 내가 접속한 IP. 즉, 서버의 IP가 나와서 당황했다..

 

import java.net.InetAddress;

public class Sample {

	public static void main(String[] args) {

		try {
			// InetAddress 틀래스의 인스턴스 를 생성
			InetAddress myIP = InetAddress.getLocalHost();
			
			// getHostAddress() 사용중인 PC의 IP주소를 얻어온다.
			String strIPAddress = myIP.getHostAddress();
			System.out.println("MY PC IPADDRESS : " + strIPAddress);
			
			// getHostName() 사용중인 PC의 이름을 얻어온다.
			//(이름은 네트워크공유등에서 사용되는 이름이다.)
			String strName = myIP.getHostName();
			System.out.println("myIP.getHostName() : " + strName);

			//getAllByName DNS를 통한 원격지 사이트의 IP 주소를 가지고 온다.
			InetAddress[] IPAList = InetAddress.getAllByName("www.google.com");
			for(InetAddress i : IPAList) {
				System.out.println("www.google.com IPADDRESS : " + i.getHostAddress());
			}
		
		} catch (Exception e) {
			System.out.println("예외 발생 : "+e.getLocalizedMessage());
		}

		
	}
}

 

 

 


 

 

 

-클라이언트의 IP 가져오기.

import javax.servlet.http.HttpServletRequest;


private String getClientIP(HttpServletRequest request) {
    String ip = request.getHeader("X-Forwarded-For");
    System.out.println("> X-FORWARDED-FOR : " + ip);

    if (ip == null)	ip = request.getHeader("Proxy-Client-IP");
	else System.out.println("> Proxy-Client-IP : " + ip);
    
    if (ip == null) ip = request.getHeader("WL-Proxy-Client-IP");
    else System.out.println(">  WL-Proxy-Client-IP : " + ip);
    
    if (ip == null) ip = request.getHeader("HTTP_CLIENT_IP");
    else System.out.println("> HTTP_CLIENT_IP : " + ip);
    
    if (ip == null) ip = request.getHeader("HTTP_X_FORWARDED_FOR");
    else System.out.println("> HTTP_X_FORWARDED_FOR : " + ip);
    
    if (ip == null) ip = request.getRemoteAddr();
    else System.out.println("> getRemoteAddr : "+ip);
    
    System.out.println("> Result : IP Address : "+ip);

    return ip;
}



public class getClientIPSample {

	public static void main(String[] args) {
		getClientIP(request);
	}
}

 

 

 

 

 

 

 


 

출처 :: https://linked2ev.github.io/java/2019/05/22/JAVA-1.-java-get-clientIP/

https://hey79.tistory.com/57


개발 공부를 위한 블로그 입니다. 

오류가 있다면 댓글로 알려주세요! 

감사합니다.

728x90