Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Chương trình Java hiển thị Hostname và địa chỉ IP


Để hiển thị Hostname và địa chỉ IP trong Java, mã như sau:

Ví dụ

import java.net.*; public class Demo{    public static void main(String[] args){       try{          InetAddress my_address = InetAddress.getLocalHost();          System.out.println("The IP address is : " + my_address.getHostAddress());          System.out.println("The host name is : " + my_address.getHostName());       }       catch (UnknownHostException e){          System.out.println( "Couldn't find the local address.");       }    } }

Kết quả

The IP address is : 127.0.0.1 The host name is : jdoodle

Lớp Demo chứa hàm main. Trong main, khối try và catch định nghĩa. Trong try, thể hiện InetAddress tạo, getLocalHost lấy địa chỉ host và hostname. Nếu thuộc tính không tìm thấy, catch bắt ngoại lệ in thông báo.