Home > JAVA > เริ่มต้นเขียน Java network Programming ด้วย Class InetAddress

เริ่มต้นเขียน Java network Programming ด้วย Class InetAddress

December 9, 2009 No Comments

Class หนึ่งใน java.net ที่ชื่อว่า InetAddress ซึ่งสามารถจัดการ Internet addresses ทั้ง host names และ IP addresses. โดยใช้ Static method ที่มีชื่อว่า getByName ซึ่ง class จะไปถาม DNS (Domain Name System) ว่ามี ชื่อ host ที่ป้อนเข้าไปมีไอพีอะไร ซึ่งค่าที่ได้รับกลับมาจะอยู่ใน object InetAddress โดยแสดงเป็นหมายเลขไอพี โดยที่เราจะสามารถแสดงผลได้อย่างง่ายโดยใช้ method println
ตั้งแต่ method getByName จะต้องมีการ throws ตรวจสอบความผิดพลาดที่อาจเกิดขึ้นได้โดยใช้
exception UnknownHostException ถ้า host name ดังกล่าวไม่มี ซึ่งก็จำเป็นที่จะต้องทำการ catch เพื่อแสดงข้อผิดพลาดนี้
โค้ดตัวอย่างการใช้

import java.net.*;

import java.util.*;

public class IPFinder

{

public static void main(String[] args)

{

String host;

Scanner input =new Scanner(System.in);

System.out.print("\n\nEnter host name:");

host =input.next();

try

{

InetAddress address= InetAddress.getByName(host);

System.out.println("IP address:"+address.toString());

}

catch (UnknownHostException uhEX)

{

System.out.println("Could not find"+host);

}

}

}

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

inet

Tags: , , , , , ,

Tags: .class dns inet ip JAVA java network ภาษา 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>