노출되는 이미지가 불편하시겠지만 양해를 구합니다. 노출, 클릭등에 관한 자료로 활용 중입니다.


Java,  Ip Address 가져오기


- 다중 Network Interface를 갖고 있는 경우에 생기는  문제 


1. 일반적인 접근

  InetAddress ip;
  String hostname;
  String ipString ;
  
  ip = InetAddress.getLocalHost();
  hostname = ip.getHostName();
  ipString = ip.toString();

 System.out.println("is contain?  " + ipString.contains("192.168.") );


2. 다중 Network Interface 찾기

public class GetIpAddress {

    public static void main(String args[]) throws SocketException  {

    	System.out.println( "isSame = " + isSame("192.168.0.13") ); 
    	
    }

    static boolean isSame(String checkIp) throws SocketException {
    	
    	String interfaceIp=null;

    	// NetworkInterface.getNetoworkInterfaces()
        Enumeration nets = NetworkInterface.getNetworkInterfaces();
        
        for (NetworkInterface netint : Collections.list(nets)) {
            interfaceIp = displayInterfaceInformation(netint);
            if ( interfaceIp != null ) {
            	if( interfaceIp.contains(checkIp) )
            		return true;
            }
        }
        return false;
    }

    // NetworkInterface : getDisplayName(), getInetAddresses()
    static String displayInterfaceInformation(NetworkInterface netint) throws SocketException {

    	System.out.printf("Display name: %s \n", netint.getDisplayName());
    	//System.out.printf("Name: %s\n", netint.getName());

        Enumeration inetAddresses = netint.getInetAddresses();
        for (InetAddress inetAddress : Collections.list(inetAddresses)) {
        	
        	// only ipv4
        	if ( inetAddress instanceof Inet4Address ) {
        		System.out.printf("InetAddress: %s\n", inetAddress);
        		return inetAddress.toString();
        	}
        }
        return null;
     }

}


블로그 이미지

StartGuide

I want to share the basic to programming of each category and how to solve the error. This basic instruction can be extended further. And I have been worked in southeast Asia more than 3 years. And I want to have the chance to work another country.

,