Quản lý địa chỉ kết nối mạng InetAdress, URL, 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.

ppt46 trang | Chia sẻ: nguyenlam99 | Lượt xem: 873 | Lượt tải: 0download
Bạn đang xem trước 20 trang tài liệu Quản lý địa chỉ kết nối mạng InetAdress, URL, URLConnection, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
Quản lý địa chỉ kết nối mạng InetAdress, URL, URLConnection Nội dungIPDNSInetAddressURLURLConnectionIPv4*Địa chỉ IPv4LớpCấu trúc địa chỉ IPFormatSố bit mạng/sốbit hostTổng số mạng/lớpTổng số host/mạngVùng địa chỉ IPA0|netid|hostidN.H.H.H 7/2427-2=126224-2=17.777.2141.0.0.1-126.0.0.0B1|0|netid|hostidN.N.H.H 14/16214-2=16382216-2=65.643128.1.0.0-191.254.0.0C1|1|0|netid|hostidN.N.N.H22/8 222-2=419430228-2=245192.0.1.0-223.255.254.0D1|1|1|0| địa chỉMulticast- ---224.0.0.0-239.255.255.255E1|1|1|1- ---240.0.0.0-254.255.255.255Loopback-- ---127.x.x.x*DNS: Domain Name SystemChức năngÁnh xạ (tên miền, dịch vụ) sang giá trị, ví dụ,,(www.cs.yale.edu, Addr) -> 128.36.229.30(cs.yale.edu, Email) -> netra.cs.yale.edu(netra.cs.yale.edu, Addr) -> 128.36.229.21Tại sao phải dùng tên thay cho địa chỉ IP?routersDNSTên miền, dịch vụ, địa chỉserversclients*DNS: Domain Name SystemLược đồ tên miền (IANA, ICANN)Nslookup (Domain/IP)*Quản lý tên miềnMỗi nhóm tên (Zone) có một server chứng thực tênMỗi Zone được ủy quyền chứng thực một tập tên miền. Một Zone*Nhóm Zone gốc và Server13 servers quản lý zone gốc trên toàn cầu*Liên kết giữa các sever DNSMỗ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ếpTên miềm cấp cao*Ví dụ xác định tên miềnLớp InetAddress Biểu diễn và quản lý địa chỉ IP: java.net.InetAddressCho 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,ServerSocketTạo đối tượng InetAddressesKhô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 UnknownHostExceptionInetAddress 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ầnpublic String getHostName()public byte[] getAddress()public String getHostAddress()Phương thức kiểm trapublic boolean isReachable(int timeout) throws IOException public boolean isMulticastAddress()public boolean isSiteLocalAddress() NetworkInterfacetry { 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." ); } *NetworkInterfaceimport 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); } } } *Cổng ứng dụngMộ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ứcMỗ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"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ứcTên miềnCổng Đường dẫnChuỗi truy vấnVí dụ URL https://metalab.unc.edu/nywc/comps.phtml?category=Choral+WorksThe java.net.URL classĐối tượng biểu diễn URLCho phép kết nối tới serverCó các phương thức Tạo một đối tượng URL mớiPhân tích các thành phần của URLLấy luồng nhập để đọc dữ liệu từ serverQuản lý dữ liệu và giao thứcDữ 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 URLpublic 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 MalformedURLExceptionpublic 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("");}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(""); URL u2 = new URL(u1, ”books.html");}catch (MalformedURLException e) {}Thao tác thành phần URLpublic String getProtocol()public String getHost()public int getPort() public String getFile()public String getRef()public String getQuery()Ví dụtry { URL u = new URL(" "); 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ừ serverpublic final InputStream openStream() throws IOExceptionpublic 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 URLCá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+ComposersLớp URLEncoderCho phép mã hóa URL theo khuôn dạngx-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+ComposersLớp URLDecoderGiả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 URLConnectionCho 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ệuMặ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 URLConnectionTạ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 URLConnectionpublic 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(“”); 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 Headerpublic 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(""); 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]; if((i>=1)&&(i=128)) System.out.println(host+" thuoc dia chi lop B"); if((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 PCMy address is 192.168.1.6-64 -88 1 6

Các file đính kèm theo tài liệu này:

  • pptchuong_5_inetaddress_url_9109.ppt
Tài liệu liên quan