Cách lấy địa chỉ IP và hostname của máy trong Java?

Hôm nay đang làm dự án thì có một task nhỏ cần giải quyết vấn đề rằng khi load trang web thì tại trang chủ nó sẽ show ra một popup thông báo, có hai nút, close và môt ô checkbox tick vào để lần sau không cần phải hiển thị popup đó nữa trong vòng 1 ngày. Vậy là hướng giải quyết sẽ liên quan đến địa chỉ ip, và hostname cần dùng đến. Còn chi tiết cách làm để tính lượt view hay một ví dụ trong dự án tôi nói ở trên thì sẽ viết chi tiết những bài sau.

Cách lấy địa chỉ IP và hostname

Dưới đây là cách lấy địa chỉ IP cũng như hostname của mình tron java bằng cách thực hiện đoạn code bên dưới:

package com.itphutran.app;
 
import java.net.InetAddress;
 
class IPAddressExample {
    public static void main(String args[]) throws Exception {
        InetAddress inetAddress = InetAddress.getLocalHost();
        System.out.println("IP Address:- " + inetAddress.getHostAddress());
        System.out.println("Host Name:- " + inetAddress.getHostName());
    }
}

Output:

IP Address:- 192.168.1.21
Host Name:- DESKTOP-XXXXXX

Ngoài ra, chúng ta cũng có thể lấy tên hostname bằng cách khác như sau:

private String getComputerName()
{
    Map<String, String> env = System.getenv();
    if (env.containsKey("COMPUTERNAME"))
        return env.get("COMPUTERNAME");
    else if (env.containsKey("HOSTNAME"))
        return env.get("HOSTNAME");
    else
        return "Unknown Computer";
}

 

Có thể tạo thành một common class:

package com.itphutran.cmm.util;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.Map;

public class AddressUtil {

	public static String getComputerName() {
		Map<String, String> env = System.getenv();
		if (env.containsKey("COMPUTERNAME")) {
			return env.get("COMPUTERNAME");
		} else if (env.containsKey("HOSTNAME")) {
			return env.get("HOSTNAME");
		} else {
			return "Unknown Computer";
		}
	}

	public static String getIpClient() {
		String ip = "";
		try {
			Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
			while (interfaces.hasMoreElements()) {
				NetworkInterface iface = interfaces.nextElement();
				// filters out 127.0.0.1 and inactive interfaces
				if (iface.isLoopback() || !iface.isUp())
					continue;

				Enumeration<InetAddress> addresses = iface.getInetAddresses();
				while (addresses.hasMoreElements()) {
					InetAddress addr = addresses.nextElement();

					if (addr instanceof Inet6Address)
						continue;

					ip = addr.getHostAddress();
				}
			}
		} catch (SocketException e) {
			throw new RuntimeException(e);
		}
		return ip;
	}
}

 

Happy coding!

0 0 đánh giá
Đánh giá bài viết
Theo dõi
Thông báo của
guest
0 Góp ý
Phản hồi nội tuyến
Xem tất cả bình luận
x