Java Network Programming
Nguy n Quang Hùng (c p nh t)
HCMC University of Technology – Faculty of
Information Technology
L P TRÌNH M NG TRÊN JAVA
Gói java.net
InetAddress
ServerSocket
Socket
URL
URLConnection
DatagramSocket
HCMC University of Technology – Faculty of
Information Technology
L P TRÌNH M NG TRÊN JAVA
InetAddress class
Class mô t v đa ch IP (Internet Protocol)
Các ph ng th c ươ getLocalHost, getByName, hay
getAllByName đ t o m t InetAddress instance:
public static InetAddess
InetAddress.getByName(String hostname)
public static InetAddess []
InetAddress.getAllByName(String hostname)
public static InetAddess InetAddress.getLocalHost()
Đ l y đa ch IP hay tên dùng các ph ng th c: ươ
getHostAddress()
getHostName()
HCMC University of Technology – Faculty of
Information Technology
L P TRÌNH M NG TRÊN JAVA
In đa ch IP c a localhost
import java.net.*;
public class HostInfo {
public static void main(String args[]) {
HostInfo host = new HostInfo();
host.init();
}
public void init() {
try {
InetAddress myHost =
InetAddress.getLocalHost();
System.out.println(myHost.getHostAddress());
System.out.println(myHost.getHostName());
} catch (UnknownHostException ex) {
System.err.println("Cannot find local
host");
}
}
}
HCMC University of Technology – Faculty of
Information Technology
Ví d 1: L y đa ch c a local/remote host
1. public class Sample1 {
2. public static void main (String[] args) {
3. try {
4. InetAddress localAddr = InetAddress.getLocalHost();
5. System.out.println( "Local Host Address (Host/IP): "
6. + localAddr.toString() );
7. InetAddress remoteAddr =
8. InetAddress.getByName("www.vnn.vn");
9. System.out.println( "Web Server IP: "
10. + remoteAddr.toString() );
11. }
12. catch (UnknownHostException ex) {ex.printStackTrace(); }
13. }// end main
14. }// End class