java.net
패키지를 활용하면 이러한 네트워크 어플리케이션의 데이터 통신 부분을 쉽게 작성할 수 있다.0~255(8bit).0~255.0~255.0~255
&
로 연산하면 IP 주소에서 네트워크 주소만을 뽑아낼 수 있다.&
연산자는 bit의 값이 모두 1일 때만 1을 결과로 얻으므로 IP주소의 마지막 8bit는 모두 0이 된다.192.168.10
)이고, 호스트 주소는 마지막 8bit(1
)임을 알 수 있다.자바에서는 IP주소를 다루기 위한 클래스로 inetAddress
를 제공하며 다양한 메서드를 제공하고 있다.
package _ch16;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
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.200.107
toString() :www.naver.com/223.130.200.107
getAddress() :[-33, -126, -56, 107]
getAddress()+256 :223.130.200.107.
getHostName() :mycom
getHostAddress() :172.30.1.51
ipArr[0] :www.naver.com/223.130.200.107
ipArr[1] :www.naver.com/223.130.195.200
www.naver.com
)에 여러 IP주소가 매핑될 수 있고 또 그 반대의 경우도 가능하기 때문에 전자의 경우 getAllByName()
을 통해 모든 IP주소를 얻을 수 있다.getLocalHost()
를 통해 호스트명과 IP주소를 알아낼 수 있다.프로토콜://호스트명:포트번호/경로명/파일명?쿼리스트링#참조
http://www.codechobo.com:80/sample/hello.html?referer=codechobo#index1
http
www.codechobo.com
80
/sample/
hello.html
referer=codechobo
index1
URL url = new URL("http://www.codechobo.com:80/sample/hello.html?referer=codechobo#index1");
URL url = new URL("www.codechobo.com", "/sample/hello.html");
URL url = new URL("http", "www.codechobo.com", "/sample/hello.html");
package _ch16;
import java.net.URL;
public class NetworkEx2 {
public static void main(String[] args) throws Exception {
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());
System.out.println("url.getDefaultPort() : " + url.getDefaultPort());
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());
System.out.println("url.toURI() : " + url.toURI());
}
}
url.getAuthority() : www.codechobo.com:80
url.getDefaultPort() : 80
url.getPort() : 80
url.getFile() : /sample/hello.html?referer=codechobo
url.getHost() : www.codechobo.com
url.getPath() : /sample/hello.html
url.getProtocol() : http
url.getQuery() : referer=codechobo
url.getRef() : index1
url.getUserInfo() : null
url.toExternalForm() : http://www.codechobo.com:80/sample/hello.html?referer=codechobo#index1
url.toURI() : http://www.codechobo.com:80/sample/hello.html?referer=codechobo#index1
HttpURLConnection
과 JarURLConnection
이 있다.openConnection()
은 HttpURLConnection을 반환한다.URLConnection
을 통해 사용해서연결하고자 하는 자원에 접근하고 읽기, 쓰기가 가능하다.package _ch16;
import java.net.URL;
import java.net.URLConnection;
public class NetworkEx3 {
public static void main(String[] args) {
URL url = null;
String address = "http://google.com";
try {
url = new URL(address);
URLConnection conn = url.openConnection();
System.out.println("conn.toString() : " + conn.toString());
System.out.println("getAllowUserInteraction() : " + conn.getAllowUserInteraction());
System.out.println("getConnectTimeOut() : " + conn.getConnectTimeout());
System.out.println("getContent() : " + conn.getContent());
System.out.println("getContentEncoding() : " + conn.getContentEncoding());
System.out.println("getContentType() : " + conn.getContentType());
System.out.println("getDate() : " + conn.getDate());
System.out.println("getDefaultAllowUserInteraction() : " + conn.getDefaultAllowUserInteraction());
System.out.println("getDoInput() : " + conn.getDoInput());
System.out.println("getDoOutput() : " + conn.getDoOutput());
System.out.println("getExpiration() : " + conn.getExpiration());
System.out.println("getHeaderFields() : " + conn.getHeaderFields());
System.out.println("getIfModifiedSince() : " + conn.getIfModifiedSince());
System.out.println("getLastModified() : " + conn.getLastModified());
System.out.println("getReadTimeout() : " + conn.getReadTimeout());
System.out.println("getURL() : " + conn.getURL());
System.out.println("getUseCaches() : " + conn.getUseCaches());
} catch (Exception e) {
e.printStackTrace();
}
}
}
conn.toString() : sun.net.www.protocol.http.HttpURLConnection:http://google.com
getAllowUserInteraction() : false
getConnectTimeOut() : 0
getContent() : sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@735b478
getContentEncoding() : null
getContentType() : text/html; charset=ISO-8859-1
getDate() : 1707649206000
getDefaultAllowUserInteraction() : false
getDoInput() : true
getDoOutput() : false
getExpiration() : 0
getHeaderFields() : {Transfer-Encoding=[chunked], null=[HTTP/1.1 200 OK], Server=[gws] ...
getIfModifiedSince() : 0
getLastModified() : 0
getReadTimeout() : 0
getURL() : http://www.google.com/
getUseCaches() : true
package _ch16;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
public class NetworkEx4 {
public static void main(String[] args) {
URL url = null;
BufferedReader input = null;
String address = "http://www.google.com";
String line = "";
try {
url = new URL(address);
input = new BufferedReader(new InputStreamReader(url.openStream()));
while((line=input.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Malformed- URLException
이 발생한다.BufferedReader
를 사용했다.outputStream()
을 호출해 URL의 InputStrea을 얻은 이후로는 파일로부터 데이터를 읽는 것과 다르지 않다.openStream()
은 openConnection()
을 호출해서 URLConnection을 얻은 다음 여기에 다시 getInputStream()
을 호출한 것이다.InputStream in = url.openStream();
// 위와 아래의 코드는 같은 작업을 수행한다.
URLConnection conn = url.openConnection();
InputStream in = conn.getInputStream();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Google</title>
</head>
<body>
<img src="https://www.google.com/images/branding/googlelogo/
2x/googlelogo_light_color_92x30dp.png" alt="Google Logo">
</body>
</html>
package _ch16;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
public class NetworkEx5 {
public static void main(String[] args) {
URL url = null;
InputStream in = null;
FileOutputStream out = null;
String address = "http://google.com";
int ch = 0;
try {
url = new URL(address);
in = url.openStream();
out = new FileOutputStream("google.zip");
while((ch=in.read()) != -1) {
out.write(ch);
}
in.close();
out.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
FileReader
가 아닌 FileOutputStream
을 사용했다.