남궁성님의 Java의 정석(3rd Edition)을 보고 정리한 글입니다.
자바에서 제공하는 java.net 패키지를 사용하면 네트워크 애플리케이션의 데이터 통신 부분을 쉽게 작성할 수 있다.
java.net 패키지를 알아보기 전에 네트워크 모델과 IP 주소에 대해 알아보자.
1. 네트워크 모델 / IP 주소
a. 클라이언트(Client)/서버(Server)
- 서버는 서비스를 제공하는 컴퓨터
- 클라이언트는 서비스를 사용하는 컴퓨터
- 안정적인 서비스의 제공이 가능하다.
- 공유 데이터의 관리와 보안이 용이하다.
- 서버구축비용과 관리비용이 든다.
b. P2P 모델(peer-to-peer model)
- 별도의 서버없이 각 클라이언트가 서버역할을 동시에 수행하는 모델
- 서버구축 및 운용비용을 절감할 수 있다.
- 자원의 활용을 극대화 할 수 있다.
- 자원의 관리가 어렵다.
- 보안이 취약하다.
c. IP 주소
- 컴퓨터를 구별하는데 사용되는 고유한 값으로 인터넷에 연결된 모든 컴퓨터는 IP 주소를 갖는다.
- ip주소는 4byte(32bit)로 구성되어 있으며, 1byte 단위의 정수가 .(마침표)를 구분자로 표현한다.
네트워크 주소와 호스트 주소
- ip주소는 네트워크 주소, 호스트 주소로 나눌 수 있다.
- 네트워크 주소가 같은 두 호스트는 같은 네트워크에 존재한다.
- ip주소와 서브넷마스크를 & 연산하면 네트워크 주소를 얻을 수 있다.
- 192.168.10.100을 2진수로 변환하면 11000000 10101000 00001010 01100100
- 255.255.255.0을 2진수로 변환하면 11111111 11111111 11111111 00000000
연산 결과를 보면 네트워크 주소는 192.168.10(24비트), 호스트 주소는 100(마지막 8비트)
그러므로 같은 네트워크 주소에 포함 가능한 호스트는 255개인데 0은 네트워크 자신을 나타내고, 255는 브로드캐스트 주소로 사용되기때문에 총 254개의 호스트를 포함시킬 수 있다.
2. java.net 패키지
a. InetAddress
자바에서는 ip주소를 다루기 위한 클래스로 InetAddress를 제공한다.
메서드 | 설명 |
byte[] getAddress() | ip주소를 byte 배열로 반환 |
static InetAddress[] getAllByName(String host) | 도메인명(host)에 지정된 모든 호스트의 ip주소를 배열에 반환 |
static InetAddress getByAddress(byte[] addr) | byte 배열을 통해 ip 주소 반환 |
static InetAddress getByName(String host) | 도메인명(host)를 통해 ip 주소를 반환 |
String getCanonicalHostName() | FQDN(fully qualifiled domain name)을 반환 |
String getHostAddress() | 호스트의 ip주소를 반환 |
String getHostName() | 호스트의 이름을 반환한다. |
static InetAddress getLocalHost() | 지역호스트의 ip주소를 반환한다. |
boolean isMulticastAddress() | ip주소가 멀티캐스트 주소인지 알려준다 |
boolean isLoopbackAddress() | ip주소가 loopback 주소(127.0.0.1)인지 알려준다. |
예제코드
public class NetworkEx1 {
public static void main(String[] args) {
InetAddress ip = null;
InetAddress[] ipArr = null;
try {
ip = InetAddress.getByName("www.naver.com");
System.out.println("getHostName(): " + ip.getHostName());
System.out.println("getHostAddress(): " + ip.getHostAddress());
System.out.println("toString(): " + ip.toString());
byte[] ipAddr = ip.getAddress();
System.out.println("getAddress(): " + Arrays.toString(ipAddr));
String result = "";
for (int i = 0; i < ipAddr.length; i++) {
result += (ipAddr[i] < 0) ? ipAddr[i] + 256 : ipAddr[i];
result += ".";
}
System.out.println("getAddress() + 256 : " + result);
System.out.println();
} catch (UnknownHostException e) {
e.printStackTrace();
}
try {
ip = InetAddress.getLocalHost();
System.out.println("getHostName(): " + ip.getHostName());
System.out.println("getHostAddress(): " + ip.getHostAddress());
System.out.println();
} catch (UnknownHostException e) {
e.printStackTrace();
}
try {
ipArr = InetAddress.getAllByName("www.naver.com");
for (int i = 0; i < ipArr.length; i++) {
System.out.println("ipARR[" + i + "] :" + ipArr[i]);
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
실행결과
getHostName(): www.naver.com
getHostAddress(): 223.130.195.200
toString(): www.naver.com/223.130.195.200
getAddress(): [-33, -126, -61, -56]
getAddress() + 256 : 223.130.195.200.
getHostName(): DESKTOP-G9CP64C
getHostAddress(): 192.168.10.21
ipARR[0] :www.naver.com/223.130.195.200
ipARR[1] :www.naver.com/223.130.200.107
b. URL(Uniform Resource Locator)
- 인터넷에 존재하는 서버들의 자원에 접근할 수 있는 주소
- ex) httpL//www.codechobo.com:80/sample/hello.html?referer=javachobo#index1
- 프로토콜: 자원에 접근하기 위해 서버와 통신하는데 사용된 통신규약(ex)http
- 호스트명: 자원을 제공하는 서버의 이름(ex)www.javachobo.com
- 포트번호: 통신에 사용되는 서버의 포트번호(ex)80
- 경로명: 접근하려는 자원이 저장된 서버상의 위치(ex)/sample/
- 파일명: 접근하려는 자원의 이름(ex)hello.html
- 쿼리: URL에서 ‘?’ 이후의 부분(referer=javachobo)
- 참조: URL에서 ‘#’이후의 부분(index1)
예제코드
public class NetworkEx1 {
public static void main(String[] args) throws IOException, URISyntaxException {
URL url = new URL("http://www.codechobo.com:80/sample/hello.html?referer=codechobo#index1");
System.out.println("url.getAuthority() = " + url.getAuthority()); // 호스트 + 포트
System.out.println("url.getContent() = " + url.getContent()); // content 반환
System.out.println("url.getDefaultPort() = " + url.getDefaultPort()); // URL 기본 포트 반환
System.out.println("url.getPort() = " + url.getPort()); // 포트 반환
System.out.println("url.getFile() = " + url.getFile()); // 파일명 반환
System.out.println("url.getHost() = " + url.getHost()); // 호스트명 반환
System.out.println("url.getPath() = " + url.getPath()); // 경로명 반환
System.out.println("url.getProtocol() = " + url.getProtocol()); // 프로토콜 반환
System.out.println("url.getQuery() = " + url.getQuery()); // 쿼리 반환
System.out.println("url.getRef() = " + url.getRef()); // 참조 반환
System.out.println("url.getUserInfo() = " + url.getUserInfo()); // 사용자정보 반환
System.out.println("url.toExternalForm() = " + url.toExternalForm()); // URL을 문자열로 변환하여 반환
System.out.println("url.toURI() = " + url.toURI()); // URL을 URI로 변환하여 반
}
}
c. URLConnection
- 애플리케이션과 URL간의 통신연결을 위한 추상 클래스
- HttpURLConnection, JarURLConnection 등도 URLConnection의 구현
예제코드
public class NetworkEx1 {
public static void main(String[] args) throws IOException, URISyntaxException {
URL url = null;
String address = "http://www.codechobo.com/sample/hello.html";
try {
url = new URL(address);
URLConnection conn = url.openConnection();
System.out.println("conn.toString() = " + conn.toString());
System.out.println("conn.getAllowUserInteraction() = " + conn.getAllowUserInteraction()); // UserInteraction의 허용여부 반허ㅏㄴ
System.out.println("conn.getConnectTimeout() = " + conn.getConnectTimeout()); // 연결종료시간을 ms 반환
System.out.println("conn.getContent() = " + conn.getContent()); // content 객체 반환
System.out.println("conn.getContentEncoding() = " + conn.getContentEncoding()); // content의 인코딩 반환
System.out.println("conn.getContentLength() = " + conn.getContentLength()); // content 크기 반환
System.out.println("conn.getContentType() = " + conn.getContentType()); // content 타입 반환
System.out.println("conn.getDate() = " + conn.getDate()); // 헤더의 date 필드 반환
System.out.println("conn.getDefaultAllowUserInteraction() = " + conn.getDefaultAllowUserInteraction()); // defaultAllowUserInteraction 반환
System.out.println("conn.getDefaultUseCaches() = " + conn.getDefaultUseCaches()); // useCache의 디폴트 값 반환
System.out.println("conn.getDoInput() = " + conn.getDoInput()); // doInput 필드값
System.out.println("conn.getDoOutput() = " + conn.getDoOutput()); // doOutput 필드값
System.out.println("conn.getExpiration() = " + conn.getExpiration()); // 자원 만료일자를 ms로 반환
System.out.println("conn.getHeaderFields() = " + conn.getHeaderFields()); // 헤더의 모든 필드와 값이 저장된 map을 반환
System.out.println("conn.getIfModifiedSince() = " + conn.getIfModifiedSince()); // ifModifiedSince(변경 여부) 반환
System.out.println("conn.getLastModified() = " + conn.getLastModified()); // 최종변경일 반환
System.out.println("conn.getReadTimeout() = " + conn.getReadTimeout()); // 읽기제한시간의 값 반환
System.out.println("conn.getURL() = " + conn.getURL()); // URL 반환
System.out.println("conn.getUseCaches() = " + conn.getUseCaches()); // 캐쉬 사용여부 반환
} catch (Exception e) {
e.printStackTrace();
}
}
}
'Programming > Java' 카테고리의 다른 글
[Java] ArrayList와 Vector (0) | 2023.11.03 |
---|---|
[Java] DI 프레임워크 Google Guice 정리 (0) | 2023.11.03 |
[Java] 람다식(Lambda) (0) | 2023.11.03 |
[Java] 쓰레드(Thread) - 1(쓰레드 구현 방법) (0) | 2023.11.03 |
[Java] 컬렉션 프레임워크와 계층 구조 (0) | 2023.11.03 |