56
1 Computer Network Lab. Computer Network Lab. 4 장 장장장 장장 장장 이이이 이이이 이이이이 이이이

4 장 인터넷 주소 처리

  • Upload
    malia

  • View
    52

  • Download
    0

Embed Size (px)

DESCRIPTION

4 장 인터넷 주소 처리. 이원구 컴퓨터 네트워크 실험실. 4 장 . 인터넷 주소 처리. DNS, IP 주소 , 그리고 모든 것 InetAddress 클래스 IP 주소를 호스트 이름으로 전환하기 유용한 프로그램들. DNS, IP 주소 , 그리고 모든 것. 기본 용어 호스트 포트 IP 주소. DNS, IP 주소 , 그리고 모든 것 ( 계속 ). 호스트 인터넷에 연결된 장치들 . 호스트는 컴퓨터 , 라우터 , 프린터 , 팩스장치 , 워크스테이션 , 등등을 지칭. - PowerPoint PPT Presentation

Citation preview

Page 1: 4 장 인터넷 주소 처리

1

Computer Network Lab. Computer Network Lab.

4 장 인터넷 주소 처리4 장 인터넷 주소 처리

이원구컴퓨터 네트워크 실험실

이원구컴퓨터 네트워크 실험실

Page 2: 4 장 인터넷 주소 처리

2Computer Network Lab. Computer Network Lab.

4 장 . 인터넷 주소 처리

DNS, IP 주소 , 그리고 모든 것

InetAddress 클래스

IP 주소를 호스트 이름으로 전환하기

유용한 프로그램들

Page 3: 4 장 인터넷 주소 처리

3Computer Network Lab. Computer Network Lab.

DNS, IP 주소 , 그리고 모든 것

기본 용어

• 호스트

• 포트

• IP 주소

Page 4: 4 장 인터넷 주소 처리

4Computer Network Lab. Computer Network Lab.

DNS, IP 주소 , 그리고 모든 것 ( 계속 )

호스트

• 인터넷에 연결된 장치들 .

• 호스트는 컴퓨터 , 라우터 , 프린터 , 팩스장치 ,

워크스테이션 , 등등을 지칭 .

Page 5: 4 장 인터넷 주소 처리

5Computer Network Lab. Computer Network Lab.

DNS, IP 주소 , 그리고 모든 것 ( 계속 )

포트

• 호스트는 단 하나의 IP 주소를 가짐 .

• 한 IP 주소에 65,536 개의 포트가 할당 가능 .

• 다른 호스트들과 통신하기 위해 하나의 호스트에 할당된

논리적인 개념 .

Page 6: 4 장 인터넷 주소 처리

6Computer Network Lab. Computer Network Lab.

DNS, IP 주소 , 그리고 모든 것 ( 계속 )

IP 주소

• 모든 호스트는 4 바이트의 유일한 IP 주소로 식별 .

• IP 주소는 0 부터 255 사이의 값을 갖는 4 개의 부호 없는

바이트로 구성 .

Page 7: 4 장 인터넷 주소 처리

7Computer Network Lab. Computer Network Lab.

DNS, IP 주소 , 그리고 모든 것 ( 계속 )

도메인 이름과 IP 주소

• 상대 컴퓨터를 지정하는 방식

• 도메인 이름

– 사람이 사용할 수 있도록 기억하기 쉽게 영문 사용

• IP 주소

– 컴퓨터가 처리하기 쉽게 지정된 크기의 숫자 사용

Page 8: 4 장 인터넷 주소 처리

8Computer Network Lab. Computer Network Lab.

DNS, IP 주소 , 그리고 모든 것 ( 계속 )

도메인 이름• 도메인 이름

– host.domain

– hostname.department.organization.classification.country

• 예

– Bora.dacom.co.kr

– Spacelink.rmsfc.nasa.gov

• 사용자 이름

[email protected]

[email protected]

Page 9: 4 장 인터넷 주소 처리

9Computer Network Lab. Computer Network Lab.

DNS, IP 주소 , 그리고 모든 것 ( 계속 )

Domain Name System(DNS)

• 숫자형 주소를 www.blackstar.com 또는 “ star.blackstar.co

m” 와 같은 이름으로 매핑하는 시스템 .

• 각 사이트는 도메인 이름을 IP 주소로 변환 .

• 분산 데이터베이스 .

Page 10: 4 장 인터넷 주소 처리

10Computer Network Lab. Computer Network Lab.

DNS, IP 주소 , 그리고 모든 것 ( 계속 )

DNS 데이터 베이스 구조

OR

UK FR JP KR NET COM EDU GOV

AC CO GO NM RE

SUN HANNAM KAIST

EVE ADAM LINTON CSE

Page 11: 4 장 인터넷 주소 처리

11Computer Network Lab. Computer Network Lab.

DNS, IP 주소 , 그리고 모든 것 ( 계속 )

IP 주소• 인터넷 숫자

– 점으로 구분된 4 자리 숫자 (4bytes)

207.247.39.35

128.134.1.1

• 클래스– A

– B

– C

– D

– E

Page 12: 4 장 인터넷 주소 처리

12Computer Network Lab. Computer Network Lab.

DNS, IP 주소 , 그리고 모든 것 ( 계속 )

주소 형식7 비트

14 비트

24 비트

16 비트

1

1 0

1 1 0

1 1 1 0

1 1 1 1 0

21 비트 8 비트

28 비트

27 비트

netid hostid

netid hostid

netid

멀티캐스트 그룹 ID

( 나중에 사용하기 위해 예약 )

hostid

클래스 A

클래스 B

클래스 C

클래스 D

클래스 E

Page 13: 4 장 인터넷 주소 처리

13Computer Network Lab. Computer Network Lab.

DNS, IP 주소 , 그리고 모든 것 ( 계속 )

주소 범위

A 0.0.0.0 ~ 127.255.255.255

B 128.0.0.0 ~ 191.255.255.255

C 192.0.0.0 ~ 223.255.255.255

D 224.0.0.0 ~ 239.255.255.255

E 240.0.0.0 ~ 247.255.255.255

클래스 범 위

Page 14: 4 장 인터넷 주소 처리

14Computer Network Lab. Computer Network Lab.

DNS, IP 주소 , 그리고 모든 것 ( 계속 )

주소 클래스• 클래스 A

– 128 개 할당 가능– 대형 네트워크 사용

• 클래스 B– 65,532 호스트 : 256 개의 C Class 에 해당– 중형 네트워크 ( 대형 기관 ) 에 적용– 얻기 곤란 , 다수의 C Class 로 대체

• 클래스 C– 254 개의 호스트– 소형 네트워크에 적용– 바닥 상태에 근접

Page 15: 4 장 인터넷 주소 처리

15Computer Network Lab. Computer Network Lab.

DNS, IP 주소 , 그리고 모든 것 ( 계속 )

• 도메인 이름과 IP 주소 대응

– 1 : 1 대응이 원칙

– 사용자는 도메인 이름과 IP 주소 모두 사용 가능

• 네트워크의 IP 주소 관리 조직

– InterNIC(Internet Network Information Center)

등록서비스 , 디렉토리와 데이터베이스 , 정보서비스

– KRNIC

국내의 IP 주소와 도메인 이름 할당

Page 16: 4 장 인터넷 주소 처리

16Computer Network Lab. Computer Network Lab.

DNS, IP 주소 , 그리고 모든 것 ( 계속 )

IPv6 의 등장배경

• 라우팅 및 주소지정 기능의 확장

• 헤더 형식의 단순화

• 옵션기능의 개선

• QUS(Quality of Service) 제어기능 추가

• 인증 및 보안기능

Page 17: 4 장 인터넷 주소 처리

17Computer Network Lab. Computer Network Lab.

DNS, IP 주소 , 그리고 모든 것 ( 계속 )

• 라우팅 및 주소지정 기능의 확장 (128 비트 )

Register ID Provider ID Subscriber ID Subnet ID Interface ID010

0 Interface ID1111111010

Subnet ID

0000 0000IPv4 address

Flag Scop Group ID11111111

3 n m o p 125-n-m-o-pBits

Bits 10 n 118-n

1111111010Bits 10

0n

Interface ID118-n-mm

Bits96 32

Subnet Prefix 0000 0000Bits n 128-n

Bits 8 4 4 112

(c) Site-local address

(f) Multicats address

(a) Provider-Based Global unicast address

(b) Link-local address

(d) IPv4-compatible IPv6 address

(e) Subnet –router anycast address

Page 18: 4 장 인터넷 주소 처리

18Computer Network Lab. Computer Network Lab.

DNS, IP 주소 , 그리고 모든 것 ( 계속 )

• 헤더 형식의 단순화

– IPv4 의 헤더 중 일부 삭제 , 일부 옵션

– IP 패킷의 공통 처리 비용을 절감

– 주소는 4 배 증가했으나 헤더는 2 배만 증가

Page 19: 4 장 인터넷 주소 처리

19Computer Network Lab. Computer Network Lab.

DNS, IP 주소 , 그리고 모든 것 ( 계속 )

• IPv4 와 IPv6 헤더 비교3115 160

data

option (if any)

4-bitheaderlength

4-bitversion

8-bit type of service(TOS) 16-bit total length (in bytes)

16-bit identification3-bitflags

13-bit fragment offset

8-bit time to live(TTL)

8-bit protocol 16-bit header checksum

32-bit destination IP address

32-bit source IP address

20 bytes

Source Address(128)

Destination Address(128)

Payload Length(16)

Flow Label(24)

Next Header(8)

Prio(4)Version(4)

IPv6Header

ExtensionHeader

……

ExtensionHeader

Transport-levelPDU

40 Octets 0 or more

Hop Limit(8)

Page 20: 4 장 인터넷 주소 처리

20Computer Network Lab. Computer Network Lab.

DNS, IP 주소 , 그리고 모든 것 ( 계속 )

• 옵션 기능의 개선

– 인코딩 방법 개선

– 옵션 영역의 길이 제한 개선

– 새로운 옵션 추가 기능

• QOS 제어기능

– IPv4 에 존재하지 않는 새로운 기능 추가

– 송신측의 특별한 QOS 표시 가능

– 실시간 서비스 , 멀티미디어 서비스 용이

Page 21: 4 장 인터넷 주소 처리

21Computer Network Lab. Computer Network Lab.

DNS, IP 주소 , 그리고 모든 것

• 인증 보안기능

– IPSEC

AH(Authentication Header)

EPS(Encapsulation Security Payload)

IPv4 옵션 , IPv6 필수

인증 , 무결성 , 기밀성 서비스 제공

Page 22: 4 장 인터넷 주소 처리

22Computer Network Lab. Computer Network Lab.

InetAddress 클래스

Java.net 패키지

ContenHandler

DatagramPacket

DatagramSocket MulticastSocket

DatagramSocketImpl

InetAddress

Object SeverSocket

Socket

SocketImpl

URL

URLConnection HttpURLConnection

URLEncoder

URLStreamHandler

Page 23: 4 장 인터넷 주소 처리

23Computer Network Lab. Computer Network Lab.

InetAddress 클래스 ( 계속 )

InetAddress 클래스

• java.net.InetAddress 클래스는 IP 주소 표현 .

• 숫자형 주소를 호스트 이름으로 , 호스트 이름을 숫자형

주소로 변환

• 호스트를 식별학기 위해 소켓이나 서버소켓과 같은 다른

네트워크 클래스에 의해 사용

Page 24: 4 장 인터넷 주소 처리

24Computer Network Lab. Computer Network Lab.

InetAddress 클래스 ( 계속 )

InetAddress 클래스의 주요 메소드

메소드 설명boolean equals(InetAddress other) 현 객체가 other 객체와 같은 주소를 가지면 true,

아니면 false 를 반환 byte[] getAddress() 주소를 나타내는 4 개의 요소를 가진 바이트

배열을 반환String getHostAddress() 주소 정보를 나타내는 문자열을 반환 String getHostName() 컴퓨터 이름을 나타내는 문자열을 반환InetAddress getLocalHost() 현재 컴퓨터를 나타내는 InetAddress 객체를 반환 throws UnknownHostExceptionInetAddress getByName(String hostName) hostName 으로 지정된 컴퓨터를 나타내는 throws UnknownHostException InetAddress 객체를 반환 InetAddress[] getAllByName(String hostName) hostName 으로 지정된 모든 컴퓨터 ( 하나의 도메인 throws UnknownHostException 이름으로 여러 대의 컴퓨터를 사용하는 경우 ) 를

나타내는 InetAddress 객체들의 배열을 반환

Page 25: 4 장 인터넷 주소 처리

25Computer Network Lab. Computer Network Lab.

InetAddress 클래스 ( 계속 )

새로운 InetAddress 객체 생성하기

• 공용 (public) 생성자가 없음 .

• 3 개의 정적 메소드가 존재 .

Page 26: 4 장 인터넷 주소 처리

26Computer Network Lab. Computer Network Lab.

InetAddress 클래스 ( 계속 )

Public static InetAddress InetAddress.getByName(String h

ostname)

• 호스트 이름을 인자로 넘겨 받아 , 이에 매칭되는 IP 주소를

찾기 위해 DNS 이용 .

• 호출 예

– InetAddress address = InetAddress.getByName(“www.oreilly.com”)

Page 27: 4 장 인터넷 주소 처리

27Computer Network Lab. Computer Network Lab.

InetAddress 클래스 ( 계속 )

예제 4.1: www.oreilly.com 의 주소를 출력하는 프로그램

import java.net.*;

class oreilly {

public static void main (String args[]) {

try { InetAddress address = InetAddress.getByName("www.oreilly.com"); System.out.println(address); }

catch (UnknownHostException e) { System.out.println("Could not find www.oreilly.com"); } } }

InetAddress 객체를 생성

호스트를 발견하지 못하면 getByName() 메소드는 UnknownHostException 을 발생

출력 결과 www.oreilly.com/204.148.40.9

Page 28: 4 장 인터넷 주소 처리

28Computer Network Lab. Computer Network Lab.

InetAddress 클래스 ( 계속 )

예제 4.2 : 204.29.207.217의 주소를 출력하는 프로그램

import java.net.*;

class OreillyByAddress {

public static void main (String args[]) {

try { InetAddress address = InetAddress.getByName("204.29.207.217"); System.out.println(address); } catch (UnknownHostException e) { System.out.println("Could not find 204.29.207.217"); } }}

호스트 이름이 없는 기계에 접속할 때

수치형 IP 주소가 문자열 형태로 전달

출력 결과 : 204.29.207.217/ 204.29.207.217

Page 29: 4 장 인터넷 주소 처리

29Computer Network Lab. Computer Network Lab.

InetAddress 클래스 ( 계속 )

그 외의 메소드

• public static InetAddress[ ] getAllByName (String ho

st) throws UnknownHostExeption

• public static InetAddress getLocalHost ( ) throws Un

knownHostExeption

Page 30: 4 장 인터넷 주소 처리

30Computer Network Lab. Computer Network Lab.

InetAddress 클래스 ( 계속 )

Public static InetAddress InetAddress.getAllByName(Strin

g hostname)

• 호스트 이름과 매칭되는 모든 InetAddres 를 담고 있는

배열을 반환

• 호출 예

– InetAddress address = InetAddress.getAllByName(“www.ora.com”)

Page 31: 4 장 인터넷 주소 처리

31Computer Network Lab. Computer Network Lab.

InetAddress 클래스 ( 계속 )

예제 4.3 : www.apple.com의 모든 주소를 출력하는 프로그램

import java.net.*;

class apple {

public static void main (String args[]) {

try { InetAddress[] addresses = InetAddress.getAllByName("www.apple.com"); for (int i = 0; i < addresses.length; i++) { System.out.println(addresses[i]); } } catch (UnknownHostException e) { System.out.println("Could not find www.apple.com"); } }}

호스트 이름과 매칭되는 모든 Inet

Addres 를 담고 있는 배열을 반환

출력 결과 : www.apple.com/17.254.0.91

Page 32: 4 장 인터넷 주소 처리

32Computer Network Lab. Computer Network Lab.

InetAddress 클래스 ( 계속 )

Public static InetAddress InetAddress.getLocalHost( )

• 프로그램이 실행되고 있는 호스트의 InetAddress 반환

• 호출 예

– InetAddress thisComputer = InetAddress.getLocalHost( );

Page 33: 4 장 인터넷 주소 처리

33Computer Network Lab. Computer Network Lab.

InetAddress 클래스 ( 계속 )

예제 4.4: 로컬 호스트의 주소 찾기

import java.net.*;

class myAddress {

public static void main (String args[]) {

try { InetAddress address = InetAddress.getLocalHost(); System.out.println(address); } catch (UnknownHostException e) { System.out.println("Could not find this computer's address."); } }}

프로그램이 실행되고 있는 호스트의 InetAddress 반환

출력 결과 : sec/203.247.39.35

Page 34: 4 장 인터넷 주소 처리

34Computer Network Lab. Computer Network Lab.

InetAddress 클래스 ( 계속 )

InetAddress 객체를 얻는 기타 방법

• DatagramPacket.getAddress( )

• ServerSocket.getInetAddress( )

• SocketImpl.getInetAddress( )

• Socket.getInetAddress( )

Page 35: 4 장 인터넷 주소 처리

35Computer Network Lab. Computer Network Lab.

InetAddress 클래스 ( 계속 )

필드 값 구하기

• public String getHostName( )

• public byte[ ] getAddress( )

Page 36: 4 장 인터넷 주소 처리

36Computer Network Lab. Computer Network Lab.

InetAddress 클래스 ( 계속 )

public String getHostName( )

• InetAddress 객체의 호스트 이름을 포함하고 있는 문자열을

반환 .

• 호스트 이름이 없는 경우 , 수치형 IP 주소가 문자열

형태로 반환 .

Page 37: 4 장 인터넷 주소 처리

37Computer Network Lab. Computer Network Lab.

InetAddress 클래스 ( 계속 )

예제 4.5: 로컬 호스트의 호스트 이름을 찾는다 .import java.net.*;

class myName {

public static void main (String args[]) {

try { InetAddress address = InetAddress.getLocalHost(); System.out.println("Hello. My name is " + address.getHostName()); } catch (UnknownHostException e) { System.out.println("I'm sorry. I don't know my own name."); } }}

InetAddress 객체의

호스트 이름을

포함하고 있는

문자열을 반환 .

출력 결과 : Hello. My name is sec

Page 38: 4 장 인터넷 주소 처리

38Computer Network Lab. Computer Network Lab.

InetAddress 클래스 ( 계속 )

public byte[ ] getAddress( )

• 기계의 IP 주소를 알기 위한 메소드

• IP 주소를 부호 없는 바이트 배열의 형태로 반환

Page 39: 4 장 인터넷 주소 처리

39Computer Network Lab. Computer Network Lab.

InetAddress 클래스 ( 계속 )

예제 4.6: 로컬 기계의 IP주소 찾기

class MyAddress6 {

public static void main (String args[]) {

try {

InetAddress thisComputer = InetAddress.getLocalHost();

byte[] address = thisComputer.getAddress();

System.out.print("My address is ");

for (int i = 0; i < address.length; i++) {

int unsignedByte = address[i] < 0 ? address[i] + 256 : address[i];

System.out.print(unsignedByte + ".");

}

System.out.println();

}

부호없는 바이트의 처리 부분

IP 주소를 바이트 배열의 형태로 반환

출력 결과 : My address is 203.247.39.35.

Page 40: 4 장 인터넷 주소 처리

40Computer Network Lab. Computer Network Lab.

InetAddress 클래스 ( 계속 )

객체 메소드들

• public boolean equals(Object anyobject)

• public int hashCode( )

• Public String toString( )

Page 41: 4 장 인터넷 주소 처리

41Computer Network Lab. Computer Network Lab.

InetAddress 클래스 ( 계속 )

public boolean equals(Object anyobject)

• 동일 객체 검증 메소드

– InetAddress 클래스의 인스턴스이고 , 4 바이트의 IP 주소가

동일 .

– 호스트 이름이 같을 필요는 없음 .

Page 42: 4 장 인터넷 주소 처리

42Computer Network Lab. Computer Network Lab.

InetAddress 클래스 ( 계속 )

예제 4.7: spacecadet 와 macfaq 는 같은가 ?

class macfaq { public static void main (String args[]) { try { InetAddress macfaq = InetAddress.getByName("www.macfaq.com "); InetAddress spacecadet = InetAddress.getByName("spacecadet.cnet.com"); if (macfaq.equals(spacecadet)) { System.out.println ("www.macfaq.com is the same as spacecadet.cnet.com");} else { System.out.println ("www.macfaq.com is not the same as spacecadet.cnet.com");} }

두 객체가 같으면 true, 다르면 false

출력 결과 : Host lookup failed.

Page 43: 4 장 인터넷 주소 처리

43Computer Network Lab. Computer Network Lab.

InetAddress 클래스 ( 계속 )

public int hashCode( )

• hashAddress 객체가 해시 테이블의 키로 사용될 경우

필요한 정수 값 반환 .

• Java.util.Hashtable 의 메소드에 의해 호출 .

• Address 필드의 값 반환 .

• 16 바이트 주소로의 수정이 어려움 .

Page 44: 4 장 인터넷 주소 처리

44Computer Network Lab. Computer Network Lab.

InetAddress 클래스 ( 계속 )

Public String toString( )

• 생성 문자열

– [ 호스트 이름 /]IP 주소

• 사용법

– InetAddress thisComputer = InetAddress.getLocolHost( )

– String address = thisComputer.toString( );

Page 45: 4 장 인터넷 주소 처리

45Computer Network Lab. Computer Network Lab.

IP 주소를 호스트 이름으로 변환하기

리버스 룩업 (Reverse lookup)

• 152,2,22,3 과 같은 IP 주소를 sunsite.unc.edu 와 같은

호스트 이름으로 변환하기

• 자바 1.0 에서는 지원하지 않음

Page 46: 4 장 인터넷 주소 처리

46Computer Network Lab. Computer Network Lab.

IP 주소를 호스트 이름으로 변환하기

예제 4.8 : IP주소로부터 호스트 이름 구하기

package java.net;import java.util.StringTokenizer;

public class InetAddressFactory { public static InetAddress newInetAddress(byte addr[]) throws UnknownHostException { try { InetAddress ia = new InetAddress(); ia.address = addr[3] & 0xFF; ia.address |= ((addr[2] << 8) & 0xFF00); ia.address |= ((addr[1] << 16) & 0xFF0000); ia.address |= ((addr[0] << 24) & 0xFF000000); return ia; }

InetAddress 객체를 만들기 위해 {199.1.32.90}와 같은 배열을 사용한다

Page 47: 4 장 인터넷 주소 처리

47Computer Network Lab. Computer Network Lab.

IP 주소를 호스트 이름으로 변환하기

public static InetAddress newInetAddress(String s) throws UnknownHostException { int num_bytes_in_an_IP_address = 4; byte addr[] = new byte[num_bytes_in_an_IP_address]; StringTokenizer st = new StringTokenizer(s, "."); if (st.countTokens() != addr.length) 예외 처리 부분 ; for (int i = 0; i < addr.length; i++) { int thisByte = Integer.parseInt(st.nextToken()); if (thisByte < 0 || thisByte > 255) { 예외 처리 부분 ; if (thisByte > 127) thisByte -= 256; addr[i] = (byte) thisByte; return newInetAddress(addr); } // end newInetAddress } // end InetAddressFactory

IPv6 를 고려

표시형식이 정확한지 검사

host 199.1.32.90

Star.blackstar.com

Page 48: 4 장 인터넷 주소 처리

48Computer Network Lab. Computer Network Lab.

IP 주소를 호스트 이름으로 변환하기

예제 4.9 : 주소가 주어지면 호스트 이름을 찾는다 .

public class ReverseTest {public static void main (String args[]) { byte[] xcluster = {18, 81, 0, 21}; try { InetAddress ia = InetAddressFactory.newInetAddress(xcluster); System.out.println(ia.getHostName()); } catch (Exception e) { System.err.println(e); } String sunsite = "152.2.22.3"; try { InetAddress ia = InetAddressFactory.newInetAddress(sunsite); System.out.println(ia.getHostName()); } catch (Exception e) { System.err.println(e); } } }

Host 18.81.0.21Host not found

Host 152.2.22.3Helios.oit.unc.edu

Page 49: 4 장 인터넷 주소 처리

49Computer Network Lab. Computer Network Lab.

유용한 프로그램들

Java lookup

• 호스트 이름과 IP 주소를 상호 변환하게 하는 유닉스

유틸리티

• 모드

– 대화형 (interactive) 모드

– 명령행 (command-line) 모드

Page 50: 4 장 인터넷 주소 처리

50Computer Network Lab. Computer Network Lab.

유용한 프로그램들 ( 계속 )

예제 4.10 : javalookuppublic class javalookup { public static void main (String args[]) { if (args.length > 0) { // use command line for (int i = 0; i < args.length; i++) { lookup(args[i]); } } else { DataInputStream myInputStream = new DataInputStream(System.in); System.out.println ("Enter names and IP addresses. Enter \"exit\" to quit."); while (true) { String s; try { s = myInputStream.readLine(); } catch (IOException e) { break; } if (s.equals("exit")) break; lookup(s); } } } /* end main */

Page 51: 4 장 인터넷 주소 처리

51Computer Network Lab. Computer Network Lab.

유용한 프로그램들 ( 계속 )

private static void lookup(String s) {

InetAddress thisComputer;

byte[] address;

try {

thisComputer = InetAddress.getByName(s);

address = thisComputer.getAddress(); }

catch (UnknownHostException ue) {

System.out.println("Cannot find host " + s);

return; }

if (isHostname(s)) {

for(int i = 0; i < address.length; i++){

int unsignedByte = address[i] < 0 ? address[i] + 256 : address[i];

System.out.println(InetAddressFactory.newInetAddress(s).getHostName());

} // 예외 처리부 } } } //end lookup

IP 주소의 바이트 배열을 얻는다

IP 주소를 출력한다

Page 52: 4 장 인터넷 주소 처리

52Computer Network Lab. Computer Network Lab.

유용한 프로그램들 ( 계속 )

private static boolean isHostname(String s) {

cahr[] ca = s.toCharArray();

for(int i = 0;i < ca.length; i++) {

if (!Character.isDigit(ca[i])) {

if (ca[i] != '.') {

return true;

}

}

}

// 모든 문자가 숫자이거나 , 마침표이므로 s 는 점으로 4 분된 IP 주소이다 return false;

} //end isHostName

}//end javalookup

문자 중에 숫자가 아니거나 마침표가 아닌 것이 발견되면 s 는 호스트 이름일 것이다

Page 53: 4 장 인터넷 주소 처리

53Computer Network Lab. Computer Network Lab.

유용한 프로그램들 ( 계속 )

실행 결과

host shock.njit.eduHost not foundhost 128.235.252.184Host not foundhost Hertz.njit.eduHost not foundhost 128.235.251.11Mail-gw3.njit.eduHost cs.nyu.edu128.122.80.79

실행 결과

host shock.njit.edu128.235.252.184host 128.235.252.184Shock.njit.eduhost Hertz.njit.edu128.235.251.11host 128.235.251.11Hertz.njit.eduHost cs.nyu.edu128.122.153.79

Page 54: 4 장 인터넷 주소 처리

54Computer Network Lab. Computer Network Lab.

유용한 프로그램들 ( 계속 )

웹 서버 로그 파일 처리하기

• 원격 호스트의 IP 주소 기록

• 호스트 이름 기록을 위한 환경 제공

• IP 주소 기록 후 , 호스트 이름으로 전환

Page 55: 4 장 인터넷 주소 처리

55Computer Network Lab. Computer Network Lab.

유용한 프로그램들 ( 계속 )

표준 로그 파일 형식

• Remotehost rfc931 authuser[date] “request” status byte

– Remotehost : 클라이언트의 호스트 이름 또는 IP 주소

– Authuser : 인증에 사용된 사용자 이름

– [date] : 요청이 이루어진 날짜와 시각

– “request” : 클라이언트에서 전송되어온 요청 내용

– Status : 숫자로된 HTTP 상태 코드

– Byte : 클라이언트에게 보내진 파일의 크기

Page 56: 4 장 인터넷 주소 처리

56Computer Network Lab. Computer Network Lab.

유용한 프로그램들

예제 4.11: 웹 서버 로그 파일 처리하기

class weblog { public static void main(String args[]) {

InetAddress thisAddress;try { FileInputStream fin = new FileInputStream(args[0]); DataInputStream myInput = new DataInputStream(fin); while ((thisLine = myInput.readLine()) != null) { index = thisLine.indexOf(" ", 0); thisIP = thisLine.substring(0, index); theRest = thisLine.substring(index, thisLine.length()); try { thisAddress = InetAddress.getByName(thisIP); address = thisAddress.getAddress(); System.out.println(InetAddressFactory.newInetAddress(address).getHostName() + theRest); }//예외처리부 및 IO예외 처리부