# IP - Internet Protocol

```mermaid
graph TD
    A[Endereçamento IP] --> B[IPv4]
    A --> C[IPv6]
    B --> D[Classes A-E]
    B --> E[Máscaras]
    C --> F[Notação Hexadecimal]
    E --> G[CIDR /23]
```

### **🔢 IPv4 vs IPv6: Comparação Essencial**

| Característica | IPv4                      | IPv6                             |
| -------------- | ------------------------- | -------------------------------- |
| **Tamanho**    | 32 bits (4 octetos)       | 128 bits (8 grupos de 16 bits)   |
| **Notação**    | Decimal (192.168.1.1)     | Hexadecimal (2001:db8::1)        |
| **Máscara**    | Subnet Mask ou CIDR (/24) | Prefixo CIDR (/64)               |
| **Espaço**     | \~4.3 bilhões             | 3.4×10³⁸ endereços               |
| **Exemplo**    | `192.168.0.1/24`          | `2001:0db8:85a3::8a2e:0370:7334` |

***

### **📊 Cálculo de Máscara de Sub-rede IPv4**

#### **1. Conversão de CIDR para Máscara Decimal (Ex: /23)**

```python
def cidr_to_mask(cidr):
    mask = (0xFFFFFFFF << (32 - cidr)) & 0xFFFFFFFF
    return ".".join([str(mask >> (24 - i * 8) & 0xFF) for i in range(4)])

print(cidr_to_mask(23))  # Saída: 255.255.254.0
```

**Explicação para /23:**

* 23 bits "1" → `11111111.11111111.11111110.00000000`
* Conversão para decimal: `255.255.254.0`

#### **2. Cálculo de Hosts por Sub-rede**

```python
hosts = 2**(32 - cidr) - 2  # -2 para rede/broadcast
print(f"/23 permite {2**(32-23)-2} hosts")  # 510 hosts
```

***

### **🧮 Exemplo Prático: Sub-rede /23**

**Dado:** `192.168.10.0/23`

1. **Máscara:** 255.255.254.0
2. **Bloco de endereços:** 512 endereços (2^(32-23))
3. **Range útil:**
   * Rede: `192.168.10.0`
   * Primeiro host: `192.168.10.1`
   * Último host: `192.168.11.254`
   * Broadcast: `192.168.11.255`

```mermaid
graph LR
    N[192.168.10.0/23] --> |Intervalo| A[10.0 - 11.255]
    A --> B[Hosts: 10.1 - 11.254]
```

***

### **🔄 Conversão IPv4 para IPv6**

#### **1. Notação IPv4 Mapeada para IPv6**

```python
ipv4 = "192.168.1.1"
ipv6_mapped = "::ffff:" + ipv4
print(ipv6_mapped)  # ::ffff:192.168.1.1
```

#### **2. Conversão Hexadecimal Direta**

```python
def ipv4_to_ipv6(ipv4):
    octets = list(map(int, ipv4.split('.')))
    return "2002:{:02x}{:02x}:{:02x}{:02x}::".format(*octets)

print(ipv4_to_ipv6("192.168.1.1"))  # 2002:c0a8:0101::
```

***

### **📐 Cálculo de Sub-redes IPv6**

**Exemplo com /64 (típico para LANs):**

```python
import ipaddress
net6 = ipaddress.IPv6Network("2001:db8::/64")
print(f"Hosts possíveis: {2**(128-64)}")  # 1.8×10¹⁹ hosts!
```

**Alocação típica:**

* `/48` para ISPs
* `/56` para clientes residenciais
* `/64` por sub-rede (SLAAC)

***

### **🔧 Ferramentas Úteis**

#### **Linux:**

```bash
ipcalc 192.168.10.0/23  # Mostra range, broadcast, etc.
sipcalc 2001:db8::/64   # Para IPv6
```

#### **Windows:**

```powershell
Import-Module NetTCPIP
Get-NetIPAddress | Where-Object {$_.AddressFamily -eq 'IPv4'}
```

#### **Python (ipaddress module):**

```python
from ipaddress import IPv4Network
subnet = IPv4Network("192.168.10.0/23")
print(subnet.num_addresses)  # 512
```

***

### **📌 Tabela de Referência Rápida (CIDR IPv4)**

| CIDR | Máscara         | Hosts | Exemplo de Range            |
| ---- | --------------- | ----- | --------------------------- |
| /24  | 255.255.255.0   | 254   | 192.168.1.1 - 192.168.1.254 |
| /23  | 255.255.254.0   | 510   | 192.168.0.1 - 192.168.1.254 |
| /22  | 255.255.252.0   | 1022  | 192.168.0.1 - 192.168.3.254 |
| /30  | 255.255.255.252 | 2     | (Para links ponto-a-ponto)  |

***

### **⚠️ Armadilhas Comuns**

1. **Esquecer endereços reservados:**
   * IPv4: Rede (`x.x.x.0`) e Broadcast (`x.x.x.255`)
   * IPv6: `::1` (loopback), `fe80::/10` (link-local)
2. **Confundir notação:**
   * IPv4: `192.168.1.1/24` ≠ `192.168.1.1/255.255.255.0` (são equivalentes)
   * IPv6: `2001:db8::1/64` (zeros podem ser omitidos com `::`)
3. **Erros em cálculos manuais:**

   ```python
   # Errado! (esquecer a base binária)
   /23 != 255.255.0.0 + 255.0.0.0
   ```

***

### **🎯 Exercício Prático**

**Problema:**\
Dividir `172.16.0.0/16` em 8 sub-redes igualmente.

**Solução:**

1. Novo CIDR: `/16 + 3 bits = /19` (pois 2³=8)
2. Intervalo por sub-rede: 2^(32-19) = 8192 endereços
3. Sub-redes:

   ```python
   from ipaddress import IPv4Network
   base = IPv4Network("172.16.0.0/16")
   subnets = list(base.subnets(new_prefix=19))
   for net in subnets:
       print(net)
   ```

   **Saída:**

   ```
   172.16.0.0/19
   172.16.32.0/19
   172.16.64.0/19
   (... até 172.16.224.0/19)
   ```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://0xmorte.gitbook.io/bibliadopentestbr/conceitos/redes/ip-internet-protocol.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
