Home > JAVA > เขียนโปรแกรม Java หาไอพีของเครื่องตัวเอง

เขียนโปรแกรม 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!");
}
}
}

ผลลัพธ์การรันโปรแกรม

mylocal

Tags: , , , ,

Comments : เขียนโปรแกรม Java หาไอพีของเครื่องตัวเอง

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>