簡體   English   中英

Java-如果用戶輸入無效的IP地址或主機名,則引發異常

[英]Java - Throwing an exception if user entered invalid IP address or host name

我想拋出一個例外,當用戶輸入無效的IP地址,主機名或不完全限定的域名時,它將顯示一條錯誤消息。

我不太確定是否要使用unknownhostexception或IOException。

我嘗試執行if語句,但是我不知道Java中的“無效”是什么。

If (addr != ' not a valid IP address, host name, fully qualified domain name or entered something invalid ')
{
throw new IOException/UnknownHostException("this is invalid: " + addr); }

有人可以幫忙嗎? 提前致謝。

嘗試使用InetAddress.getByName(str)來驗證字符串。 如有必要,它將拋出UnknownHostException 我建議完全刪除您的if語句。 也許是這樣的:

public static InetAddress testAddress(String str) throws UnknownHostException {
    InetAddress add = InetAddress.getByName(str);

    // Check if IP address was simply returned, instead of host.
    if (add.getCanonicalHostName().equals(add.getHostAddress())) {
        throw new UnknownHostException(str + "is not a known host.");
    }
    return add;
}

有一個稱為regex(正則表達式)的概念,您可以在其中檢查該模式是否正確。 您可能需要尋找好的解決方案或編寫自己的正則表達式(根據我個人的觀點,這並不容易)。 但這是一個很好的起點http://www.mkyong.com/regular-expressions/how-to-validate-ip-address-with-regular-expression/ ;)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM