เขียนโปรแกรม Java หาไอพีของเครื่องตัวเอง
December 12, 2009
No Comments
ในการเขียนโปรแกรมครั้งนี้จะเป็นการใช้ method ของ Class InetAddress ที่ชื่อว่า getLocalHost() ซึ่งต้องทำการ import java.net.*; เข้ามาด้วยโดยที่หลังจากเรียกใช้แล้วจะคืนค่าเป็น address ip ของเราสามารถทำการโดยแสดงผลได้เลยโดยใช้ System.out.println ได้เลยแต่อย่าลืม try catch ด้วยนะครับ โดยใช้ Exeption ที่มีชื่อว่า UnknowHostException เพื่อไม่มี host ดังกล่าว
โค้ดโปรแกรม
import java.net.*;
public class MyLocalIPAddress
{
public static void main(String[] args)
{
try
{
InetAddress address = InetAddress.getLocalHost();
System.out.println(address);
}
catch (UnknownHostException uhEx)
{
System.out.println("Could not find local address!");
}
}
}
ผลลัพธ์การรันโปรแกรม
Tags: getLocalHost JAVA java network programming ไอพีของเครื่องตัวเอง
