2014-01-07 27 views
-1

我使用InetAddress獲取IP地址。錯誤:使用JAVA的系統的IP地址

這是我的代碼

String hostname=args[0]; 


     try { 
      InetAddress ipaddress= InetAddress.getByName(hostname); 
      System.out.println("IPADDRESS" +ipaddress.getHostAddress()); 
     } catch (UnknownHostException e) { 
      // TODO Auto-generated catch block 
      System.out.println("Could not find anything" +hostname); 
     } 

但在控制檯

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 
    at com.networking.ipaddress.IP.main(IP.java:11) 

什麼實際問題?代碼或系統有問題?

+0

如果帶有「args」,則表示默認程序參數:如果您沒有使用任何參數調用程序,則「參數」的大小爲0 amd [0]將超出數組範圍。在訪問它之前使用if(args.Length> 0)。 –

+3

是你傳遞參數值嗎? – Lakshmi

回答

0

您正在從程序參數中獲取主機名,但在啓動java時沒有將主機名指定爲程序參數,所以args []數組爲空數組,因此訪問其[0]元素會引發異常。 您必須指定主機名作爲參數傳遞給了Java在運行應用程序如下:

java YourClassFileName 192.168.1.1 
0

您可以檢查線路11類的確切地點,但顯然這是你指定的主機名的形式ARGS行陣列。

String hostname=args[0]; 

如果是main方法的args []數組,請確保在運行程序時傳遞主機名。