Quản lý địa chỉ kết nối mạng InetAdress, URL, URLConnection

Nội dung

 IP  DNS  InetAddress  URL  URLConnection

IPv4

3

Địa chỉ IPv4

Lớp Cấu trúc địa chỉ IP Format Vùng địa chỉ

Tổng số mạng/lớp Tổng số host/mạng IP

Số bit mạng/sốbi t host

0|netid|hostid N.H.H.H 7/24 27-2=126 A

224- 2=17.777.214 1.0.0.1- 126.0.0.0

1|0|netid|hostid N.N.H.H 14/16 214-2=16382 216-2=65.643 B

128.1.0.0- 191.254.0.0

1|1|0|netid|hostid N.N.N.H 22/8 28-2=245 C

222- 2=4194302 192.0.1.0- 223.255.254.0

- - - - D

1|1|1|0| địa chỉ Multicast

224.0.0.0- 239.255.255.2 55

1|1|1|1 - - - - E

240.0.0.0- 254.255.255.2 55

- - - - - 127.x.x.x

Loopba ck

DNS: Domain Name System

 Chức năng

clients

 Ánh xạ (tên miền, dịch vụ)

sang giá trị, ví dụ,,

(www.cs.yale.edu,

DNS

routers

Tên miền, dịch vụ, địa chỉ

Addr) -> 128.36.229.30 (cs.yale.edu, Email) -> netra.cs.yale.edu (netra.cs.yale.edu,

Addr) -> 128.36.229.21

servers

 Tại sao phải dùng tên thay

cho địa chỉ IP?

5

DNS: Domain Name System

 Lược đồ tên miền (IANA, ICANN)

 Nslookup (Domain/IP)

6

Quản lý tên miền

 Mỗi nhóm tên (Zone) có một server chứng thực tên  Mỗi Zone được ủy quyền chứng thực một tập tên

miền.

ộ M t Zone

7

Nhóm Zone gốc và Server

 13 servers quản lý zone gốc trên toàn cầu

8

Liên kết giữa các sever DNS

 Mỗi server biết địa chỉ server gốc.  Mỗi server gốc biết địa chỉ chính nó và địa chỉ node

con trực tiếp

Tên miềm cấp cao

9

Ví dụ xác định tên miền

10

Lớp InetAddress

 Biểu diễn và quản lý địa chỉ IP:

java.net.InetAddress

 Cho phép xác định địa chỉ IP dựa vào tên miền và

ngược lại.

 Các lớp mạng khác sử dụng nó để xác định host ở

xa.

 Ví dụ: Socket,ServerSocket…

Tạo đối tượng InetAddresses

 Không có phương thức khởi tạo.  Tất cả các đối tượng địa chỉ được tạo ra, địa chỉ

tương ứng phải được kiểm trả với DNS.

 public static InetAddress

InetAddress.getByName(String hostname)

 public static InetAddress[]

InetAddress.getAllByName(String

hostname)

 public static InetAddress

InetAddress.getLocalHost()

Tạo đối tượng: getByName()

 public static InetAddress getByName(String host)

throws UnknownHostException

InetAddress ipdntu, dntu; try { ipdntu = InetAddress.getByName(“dntu.edu.vn"); dntu = InetAddress.getByName("125.234.251.138"); } catch (UnknownHostException e) { System.err.println(e); }

Tạo đối tượng: getByName()

 public static InetAddress getByName(String host)

throws UnknownHostException InetAddress ipdntu, dntu; try {

ipdntu = InetAddress.getByName(“dntu.edu.vn"); dntu = InetAddress.getByName("118.69.218.67");

} catch (UnknownHostException e) {

System.err.println(e);

}

Phương thức lấy các thành phần

 public String getHostName()

 public byte[] getAddress()

 public String getHostAddress()

Phương thức kiểm tra

 public boolean isReachable(int timeout) throws

IOException

 public boolean isMulticastAddress()

 public boolean isSiteLocalAddress()

NetworkInterface

try { NetworkInterface ni = NetworkInterface.getByName("eth0"); if (ni == null) { System.err.println("No such interface: eth0" ); } } catch (SocketException ex) {

System.err.println("Could not list sockets." );

}

17

NetworkInterface

import java.net.*; import java.util.*; public class InterfaceLister { public static void main(String[] args) throws Exception { Enumeration interfaces =

NetworkInterface.getNetworkInterfaces( );

while (interfaces.hasMoreElements( )) { NetworkInterface ni = (NetworkInterface)

interfaces.nextElement( );

System.out.println(ni); } } }

18

Cổng ứng dụng

 Một host có một địa chỉ duy nhất để nhận dạng, làm thế

nào để đồng thời nhiều ứng dụng trên một host có thể

giao tiếp với host khác ?

 Cổng-port được sử dụng. Có 65,536 port.

 Một một dịch vụ tương ứng với một port. Ví dụ, http chạy

với port 80.

Giao thức

 Mỗi dịch vụ tương ứng với một giao thức.  Giao thức qui định 2 dịch vụ của 2 host giao tiếp

với nhau như thế nào.

 Ví dụ

 telnet, SMTP, HTTP  http://www.faqs.org/rfc/

URL

 URL-"Uniform Resource Locator", xác định tài

nguyên trên mạng Internet.

 Các thành phần của URL.

 Giao thức  Tên miền  Cổng  Đường dẫn  Chuỗi truy vấn

Ví dụ URL

http://java.sun.com/ file:///Macintosh%20HD/Java/Docs/JDK

%201.1.1%20docs/api/java.net.InetAddress.html#_top_

http://www.macintouch.com:80/newsrecent.shtml ftp://ftp.info.apple.com/pub/ mailto:elharo@metalab.unc.edu telnet://utopia.poly.edu ftp://mp3:mp3@138.247.121.61:21000/c%3a/stuff/mp3/ http://elharo@java.oreilly.com/ https://metalab.unc.edu/nywc/comps.phtml?category=Choral+Works

The java.net.URL class

 Đối tượng biểu diễn URL

 Cho phép kết nối tới server

 Có các phương thức

 Tạo một đối tượng URL mới

 Phân tích các thành phần của URL

 Lấy luồng nhập để đọc dữ liệu từ server

Quản lý dữ liệu và giao thức

 Dữ liệu và giao thức tương ứng được kiểm soát

riêng.

 Trình quản lý giao thức giao tiếp với server ở một

kênh riêng. Dữ liệu được truyền tách biệt ở một

luồng nhập riêng InputStream, ImageProducer.

Tạo đối tượng URL

 public URL(String url) throws MalformedURLException  public URL(String protocol, String host, String file) throws

MalformedURLException

 public URL(String protocol, String host, int port, String file)

throws MalformedURLException  public URL(URL u, String s) throws

MalformedURLException

 Khi máy ảo tạo ra đối tượng URL, thì đồng thời nó tìm trình quản lý giao thức tương ứng ví dụ “http” hoặc “mailto”.

 Nếu không có, hàm khởi tạo tạo ra ngoại lệ

MalformedURLException.

Ví dụ

try {

URL u = new URL("http://www.poly.edu/fall97/grad.html#cs");

} catch (MalformedURLException e) {}

Ví dụ

URL u = null; try { u = new URL("http", "www.poly.edu", "/schedule/fall97/bgrad.html#cs"); }catch (MalformedURLException e) {}

Ví dụ

URL u = null; try { u = new URL("http", "www.poly.edu", 8000,

"/fall97/grad.html#cs");

} catch (MalformedURLException e) {}

Ví dụ

try { URL u1 = new

URL("http://metalab.unc.edu/index.html");

URL u2 = new URL(u1, ”books.html"); } catch (MalformedURLException e) {}

Thao tác thành phần URL

 public String getProtocol()

 public String getHost()

 public int getPort()

 public String getFile()

 public String getRef()

 public String getQuery()

Ví dụ

try { URL u = new URL("http://www.poly.edu/fall97/grad.php?

q=idx#cs ");

System.out.println("The protocol is"+u.getProtocol()); System.out.println("The host is " + u.getHost()); System.out.println("The port is " + u.getPort()); System.out.println("The file is " + u.getFile()); System.out.println("The anchor is " + u.getRef()); System.out.println("The query is " + u.getQuery()); }catch (MalformedURLException e) { }

Đọc dữ liệu từ server

 public final InputStream openStream() throws

IOException

 public URLConnection openConnection() throws

java.io.IOException

 public final Object getContent() throws

java.io.IOException

Ví dụ

String s="ftp://it.hutech.edu.vn/quidinh.doc"; String thisLine; try{

URL u =new URL(s); try{ DataInputStream dis = new DataInputStream(u.openStream()); while((thisLine=dis.readLine())!=null) System.out.println(thisLine);

}catch(IOException e) { System.err.println(e);}

}catch(MalformedURLException e){ System.err.println(e);

}

Mã hóa URL

 Các ký tự trong bảng mã ASCII gồm a-z, A-Z, , 0-9

và $-_.!*'(), là không thay đổi.

 Các ký tự khoảng cách trắng bị biến đổi thành dấu

cộng (+).

 Các ký tự khác (ví dụ &, =, ^, #, %, ^, {, ..) bị biến

đổi thành dấu phần trăm và theo sau đó là giá trí trị

mã ASCII của nó biểu diễn ở hệ cơ số 16.

Ví dụ

 Dấu phẩy mã ASCII là (44)10 hay (2C)16 . Vì vậy,

trong URL dấu phẩy được mã là %2C.

 Chuỗi truy vấn

"Author=Sadie, Julie&Title=Women Composers" được mã là: Author=Sadie

%2C+Julie&Title=Women+Composers

Lớp URLEncoder

 Cho phép mã hóa URL theo khuôn dạng

x-www-form-url-encoded

 Phương thức tĩnh dùng mã hóa là: URLEncoder.encode(String s)

 Ví dụ String qs = "Author=Sadie, Julie&Title=Women Composers"; String eqs = URLEncoder.encode(qs); System.out.println(eqs);  Kết quả Author%3dSadie%2c+Julie%26Title%3dWomen+Composers

Lớp URLDecoder

 Giải mã chuỗi truy vấn có dạng x-www-form-url-encoded.

 Phương thức tĩnh giải mã

URLEncoder.decode(String s)

Lớp URLConnection

 Cho phép tạo kênh giao tiếp với Server (FTP,

HTTP, ...)

 Có thể gửi dữ liệu và đọc dữ liệu  Mặc định khi kết nối tới HTTP, URL sử dụng

phương thức GET.

 Đọc thông tin Header khi giao tiếp với Server.

Tạo đối tượng URLConnection

 Tạo đối tượng URL.

 Gọi phương thức openConnection()

 Đọc các trường header.

 Nhận một luồng nhập và đọc dữ liệu.

 Nhận một luồng xuất và ghi dữ liệu.

 Đóng liên kết.

Tạo đối tượng URLConnection

 public Map getHeaderFields()

 public InputStream getInputStream()

 public OutputStream getOutputStream()

 public abstract void connect() throws

IOException

Ví dụ

String s="ftp://dntu.edu.vn/thongbao.doc"; try{

URL u =new URL(s); try{

URLConnection uc=u.openConnection(); DataInputStream is; is = new DataInputStream(uc.getInputStream()); String thisLine; while((thisLine=is.readLine())!=null){ System.out.println(thisLine);

}

} catch(Exception e) { System.err.println(e); }

}catch(MalformedURLException e){System.err.println(e);}

Ví dụ

try{

URL u = new

URL(“http://www.somehost.com/cgi- bin/acgi”);

URLConnection uc = u.openConnection(); uc.setDoOutput(true); DataOutputStream dos;

dos = new DataOutputStream(uc.getOutputStream()); dos.writeByte("Herre is some data");

}catch(Exception e) {

System.err.println(e);

}

Các hàm nhận thông tin Header

public String getHeaderField(String name) public int getContentLength() public String getContentType() public String getContentEncoding() public long getExpiration() public long getDate() public long getLastModified()  Ví dụ:

 uc.getHeaderField("content-type");  uc.getHeaderField("content-encoding");

Ví dụ

try { URL u = new URL("http://www.sdexpo.com/"); URLConnection uc = u.openConnection(); uc.connect(); String key=null; for (int n = 1; (key=uc.getHeaderFieldKey(n)) != null; n++) { System.out.println(key + ": " +

uc.getHeaderField(key));

} } catch (IOException e) { System.err.println(e); }

Ví dụ

import java.net.*; public class PhanLoaiDCIP { public static void main(String[] args) { try{

if(args.length!=1) System.out.println("Cach su dung: java TimDCIP "); InetAddress host = InetAddress.getByName(args[0]); String hostName = host.getHostName(); System.out.println("Host name:"+hostName); System.out.println("Dia chi IP:"+host.getHostAddress()); byte[] b=host.getAddress(); int i=b[0]>=0?b[0]:256+b[0]; System.out.println(host+" thuoc dia chi lop A"); if((i>=1)&&(i<=126)) if((i<=191)&&(i>=128)) System.out.println(host+" thuoc dia chi lop B"); if((i<=223)&&(i>=192)) System.out.println(host+" thuoc dia chi lop C");

}catch(UnknownHostException e){

System.out.println("Khong tim thay dia chi"); return;

} }}

Ví dụ

import java.net.*; public class Local { public static void main(String[] args) { try { InetAddress me = InetAddress.getLocalHost(); System.out.println("My name is " + me.getHostName()); System.out.println("My address is " + me.getHostAddress()); byte[] address = me.getAddress(); for (int i = 0; i < address.length; i++) { System.out.print(address[i] + " "); } System.out.println(); } catch (UnknownHostException e) { System.err.println("Could not determine local address."); System.err.println("Perhaps the network is down?"); } } }

My name is PC My address is 192.168.1.6 -64 -88 1 6