
| Port 범위 | 용도 |
|---|---|
| 0 ~ 1023 | ICANN 예약(HTTP: 80, HTTPS: 443 등) |
| 1024 ~ 49151 | 등록 가능한 Port(기업/서비스) |
| 49152 ~ 65535 | 동적/개인용 포트(OS 자동 할당) |
자바에서는 java.net.InetAddress 클래스를 사용.
// 로컬 IP 주소 얻기
InetAddress local = InetAddress.getLocalHost();
System.out.println(local.getHostAddress());
// 도메인으로 IP 얻기
InetAddress naver = InetAddress.getByName("www.naver.com");
System.out.println(naver.getHostAddress());
// 하나의 도메인에 여러 IP 등록된 경우
InetAddress[] iaArr = InetAddress.getAllByName("www.google.com");
for (InetAddress ip : iaArr) {
System.out.println(ip.getHostAddress());
}
import java.net.*;
import java.io.*;
public class TcpServer {
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(50001)) {
System.out.println("[서버] 시작됨");
Socket socket = serverSocket.accept(); // 연결 대기
InetSocketAddress isa = (InetSocketAddress) socket.getRemoteSocketAddress();
System.out.println("[서버] 연결됨: " + isa.getHostName());
// 데이터 수신
DataInputStream dis = new DataInputStream(socket.getInputStream());
String message = dis.readUTF();
System.out.println("[서버] 받은 메시지: " + message);
// 데이터 전송
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
dos.writeUTF("Hello Client");
dos.flush();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.net.*;
import java.io.*;
public class TcpClient {
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 50001)) {
System.out.println("[클라이언트] 연결 성공");
// 데이터 전송
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
dos.writeUTF("Hello Server");
dos.flush();
// 데이터 수신
DataInputStream dis = new DataInputStream(socket.getInputStream());
String response = dis.readUTF();
System.out.println("[클라이언트] 받은 메시지: " + response);
} catch (UnknownHostException e) {
System.out.println("잘못된 IP 주소");
} catch (IOException e) {
System.out.println("연결 실패");
}
}
}
서버
accept()로 클라이언트 요청 수락클라이언트
// UDP 서버
import java.net.*;
public class UdpServer {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(50001);
byte[] buf = new byte[1024];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
System.out.println("[서버] 수신 대기");
socket.receive(packet);
String msg = new String(packet.getData(), 0, packet.getLength(), "UTF-8");
System.out.println("[서버] 받은 메시지: " + msg);
socket.close();
}
}
// UDP 클라이언트
import java.net.*;
public class UdpClient {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket();
byte[] buf = "Hello UDP".getBytes("UTF-8");
DatagramPacket packet = new DatagramPacket(
buf, buf.length, new InetSocketAddress("localhost", 50001));
socket.send(packet);
socket.close();
}
}
ServerSocket, SocketDatagramSocket, DatagramPacket