IP
Internet Protocol
The basic protocol of Internet communication. IPv4 (32-bit), IPv6 (128-bit).
Internet Protocol
The basic protocol of Internet communication. IPv4 (32-bit), IPv6 (128-bit).
IP (Internet Protocol) is the core protocol for exchanging data on the internet. Every network device is assigned a unique IP address, and through this address billions of devices around the world identify each other and communicate. An IP address is like a postal code of the internet, so that data packets are routed to reach their destination accurately.
IPv4, which is widely used today, is a 32-bit addressing scheme that provides about 4.3 billion (2^32) addresses. It is written as four numbers in the range 0–255 separated by dots, like 192.168.1.1. However, due to the explosive growth of internet users, IPv4 addresses were exhausted in 2011, and to solve this, IPv6, a 128-bit scheme (in the form 2001:0db8:85a3::8a2e:0370:7334), was introduced. IPv6 provides about 340 undecillion (3.4 x 10^38) addresses.
IP addresses are divided into public IPs and private IPs. A public IP is a unique address directly reachable on the internet, while a private IP (10.x.x.x, 172.16–31.x.x, 192.168.x.x) is used only within internal networks. At home or in the office, multiple devices share a single public IP through a router (NAT). A DHCP server automatically assigns IP addresses to devices connected to the network.
A subnet is a technique for dividing a large network into smaller units. The network range is expressed in CIDR (Classless Inter-Domain Routing) notation (e.g., 192.168.1.0/24), and /24 means that the first 24 bits are the network address. Understanding CIDR is essential when designing a VPC in a cloud environment and configuring firewall rules. In practice, IP geolocation is used for location-based services and for detecting abnormal access.
import socket
import ipaddress
import requests
# 내 공인 IP 확인
my_public_ip = requests.get("https://api.ipify.org").text
print(f"공인 IP: {my_public_ip}")
# 내 사설 IP 확인
my_private_ip = socket.gethostbyname(socket.gethostname())
print(f"사설 IP: {my_private_ip}")
# IP 주소 유효성 검사 및 분석
def analyze_ip(ip_str):
try:
ip = ipaddress.ip_address(ip_str)
print(f"IP: {ip}")
print(f"버전: IPv{ip.version}")
print(f"사설 IP: {ip.is_private}")
print(f"루프백: {ip.is_loopback}")
print(f"멀티캐스트: {ip.is_multicast}")
except ValueError:
print("유효하지 않은 IP 주소")
analyze_ip("192.168.1.100")
analyze_ip("8.8.8.8")
# CIDR 네트워크 분석
network = ipaddress.ip_network("192.168.1.0/24")
print(f"네트워크: {network.network_address}")
print(f"브로드캐스트: {network.broadcast_address}")
print(f"호스트 수: {network.num_addresses - 2}") # 네트워크/브로드캐스트 제외
print(f"서브넷 마스크: {network.netmask}")
# 특정 IP가 네트워크에 포함되는지 확인
if ipaddress.ip_address("192.168.1.50") in network:
print("192.168.1.50은 해당 네트워크에 속함")
# IP 지오로케이션 (무료 API)
def get_ip_location(ip):
response = requests.get(f"http://ip-api.com/json/{ip}")
data = response.json()
return f"{data['country']}, {data['city']} ({data['isp']})"
print(get_ip_location("8.8.8.8")) # United States, Ashburn (Google LLC)
# 내 공인 IP 확인 (여러 방법)
curl -s https://api.ipify.org
curl -s ifconfig.me
curl -s icanhazip.com
dig +short myip.opendns.com @resolver1.opendns.com
# 내 사설 IP 확인
ip addr show | grep "inet " | grep -v 127.0.0.1
hostname -I
ifconfig | grep "inet " | awk '{print $2}'
# 특정 IP 정보 조회 (whois)
whois 8.8.8.8
# IP 지오로케이션 확인
curl -s "http://ip-api.com/json/8.8.8.8" | jq
# 출력: {"country":"United States","city":"Ashburn",...}
# 포트 스캔 (nmap)
nmap -sP 192.168.1.0/24 # 네트워크 내 활성 호스트 탐색
nmap -p 80,443 google.com # 특정 포트 확인
# 라우팅 경로 추적
traceroute google.com
traceroute -n 8.8.8.8 # DNS 해석 없이
# 네트워크 인터페이스 설정 확인
ip route show # 라우팅 테이블
ip link show # 인터페이스 목록
# ARP 테이블 (IP ↔ MAC 매핑)
arp -a
# 서브넷 계산 (ipcalc 설치 필요)
ipcalc 192.168.1.0/24
# Network: 192.168.1.0/24
# Netmask: 255.255.255.0
# HostMin: 192.168.1.1
# HostMax: 192.168.1.254
# Broadcast: 192.168.1.255
# Hosts/Net: 254
# NAT 테이블 확인 (Linux, root 권한)
iptables -t nat -L -n
const os = require('os');
const dns = require('dns');
const https = require('https');
// 사설 IP 확인
function getPrivateIP() {
const interfaces = os.networkInterfaces();
for (const name in interfaces) {
for (const iface of interfaces[name]) {
if (iface.family === 'IPv4' && !iface.internal) {
return iface.address;
}
}
}
return '127.0.0.1';
}
console.log('사설 IP:', getPrivateIP());
// 공인 IP 확인
async function getPublicIP() {
return new Promise((resolve, reject) => {
https.get('https://api.ipify.org', (res) => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => resolve(data));
}).on('error', reject);
});
}
getPublicIP().then(ip => console.log('공인 IP:', ip));
// IP 주소 유효성 검사
function isValidIPv4(ip) {
const parts = ip.split('.');
if (parts.length !== 4) return false;
return parts.every(part => {
const num = parseInt(part, 10);
return num >= 0 && num <= 255 && part === String(num);
});
}
function isValidIPv6(ip) {
const pattern = /^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/;
return pattern.test(ip);
}
// 사설 IP 여부 확인
function isPrivateIP(ip) {
const parts = ip.split('.').map(Number);
return (
parts[0] === 10 ||
(parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) ||
(parts[0] === 192 && parts[1] === 168)
);
}
console.log(isPrivateIP('192.168.1.1')); // true
console.log(isPrivateIP('8.8.8.8')); // false
// CIDR 범위 내 IP 확인
function ipInCIDR(ip, cidr) {
const [range, bits] = cidr.split('/');
const mask = ~(2 ** (32 - parseInt(bits)) - 1);
const ipNum = ip.split('.').reduce((acc, oct) => (acc << 8) + parseInt(oct), 0);
const rangeNum = range.split('.').reduce((acc, oct) => (acc << 8) + parseInt(oct), 0);
return (ipNum & mask) === (rangeNum & mask);
}
console.log(ipInCIDR('192.168.1.50', '192.168.1.0/24')); // true
console.log(ipInCIDR('192.168.2.1', '192.168.1.0/24')); // false
"If we set the VPC CIDR to 10.0.0.0/16, we can use more than 65,000 IPs. Let's separate the public subnet as 10.0.1.0/24 and the private subnet as 10.0.10.0/24, and configure the private subnet to communicate externally through a NAT Gateway."
"In this log analysis, requests of more than 500 per minute are coming in from the same public IP. The IP geolocation check shows it appears to be an overseas VPN, so I think we should first block that IP range (/24) at the firewall and apply Rate Limiting."
"NAT and CIDR were introduced to solve the IPv4 exhaustion problem, and the transition to IPv6 is underway in the long term. On AWS, you can support IPv4/IPv6 simultaneously in dual-stack mode, and in mobile networks the share of IPv6 has actually exceeded 50%."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
A public IP can change depending on the ISP or cloud environment. Use environment variables or DNS. In Auto Scaling environments in particular, IPs change frequently.
/24 provides 256 addresses (254 usable), and /16 provides 65,536. If you allocate a range that is too narrow when designing a VPC, expanding it later is difficult. In AWS VPC, the CIDR cannot be changed after creation.
Behind a load balancer/proxy, the client IP appears as the proxy IP. You must parse the X-Forwarded-For header to get the actual client IP. However, to prevent spoofing, allow only trusted proxies.
When designing a VPC, secure a sufficient CIDR range (/16 recommended). Separate subnets by Availability Zone. Control security groups finely by IP range (/32 or /24). Elastic IP incurs costs, so release it when not in use.