Skip to content

NMAP for scanning networks

Posted by author in the category "nmap"

Disclaimer: The information in this article about NMAP is for educational and informational purposes only. It is not intended to encourage or facilitate any illegal activities, such as unauthorized scanning, hacking, or intrusion into computer systems without explicit permission. Users must comply with all applicable laws. The author disclaims any liability for misuse of the tools or techniques described. Always obtain proper authorization before using NMAP on any network or system you do not own.

NMAP is the network reconnaissance tool. You want to know what's alive on your network? What ports are open? What OS is running? NMAP answers all of it. Let's break down the commands that actually matter, how they work under the hood, and when to use each one.

Host Discovery: Finding What's Alive

ARP Scan (Local Networks)

nmap -sn -PR <target>

What it does: ARP-based host discovery on your local Ethernet segment. No port scan, just tells you which IPs are alive by getting ARP replies. Yes, you could just use arp-scan. But stick with me, this article is about NMAP, not "oH BuT theRe Are oTHer toOlS thaT YOu CAN usE TO gEt ThIS doNe".

How it works: ARP is layer-2. -PR sends ARP who-has requests for each IP. Live host? Responds with ARP reply containing MAC and IP. -sn kills port scanning, stops after host discovery and basic reporting.

Why ARP is king for local networks: it operates below IP, bypasses IP-layer filters on the same L2 broadcast domain. Fast, deterministic, reliable. ARP responses include the MAC, which you can use to identify vendor and detect proxying/NAT.

When to use: Scanning your LAN or any directly attached Ethernet/VLAN segment. Most reliable method for local host discovery - can't be filtered by host firewalls that block ICMP/TCP/UDP because ARP is resolved before IP stacks even see packets.

The catch: Won't traverse routers. Only works on local segment.

ICMP Echo Sweep (Routed Networks)

nmap -sn -PE <target-range>

What it does: ICMP Echo sweep across target range. Lists who responds.

How it works: Sends ICMP Echo Request (type 8), waits for Echo Reply (type 0). Timing and retry parameters influence detection of rate-limited systems. Yes, this is like ping on small amounts of performance enhancing drugs.

When to use: Simple, low-overhead, widely supported on routers/hosts that allow ICMP. Not reliable behind firewalls that drop ICMP.

Comparison: -PE vs -PR - ICMP is layer-3 and can be filtered. ARP can't be filtered but doesn't cross routers. Use -PR for accuracy on L2, -PE for routed networks.

Other Host Discovery Probes

These alternative probes exist because networks filter different things differently. One network might block ICMP but allow TCP. Another might block unsolicited TCP SYNs but let ACKs through. You need options.

TCP SYN Ping

nmap -sn -PS80,443 <target>

What it does: Sends TCP SYN packets to specified ports (default 80 if not specified). Any response - SYN+ACK or RST - means host is alive.

How it works: This is the first step of a normal TCP handshake. Send a SYN to a port. If the port is open, you get SYN+ACK back. If it's closed, you get RST. Either way, you know the host is up. Nmap doesn't complete the handshake - just probes and moves on.

When to use: When ICMP is blocked but you know common TCP ports (80, 443, 22) are likely to be open or at least responding. Firewalls often allow TCP to standard ports but drop ICMP entirely. This is more likely to get through than ICMP Echo.

Example scenario: Corporate network where ICMP is filtered at the perimeter but web servers (80/443) are accessible. TCP SYN to port 80 will elicit a response even if the firewall drops pings.

TCP ACK Ping

nmap -sn -PA80,443 <target>

What it does: Sends TCP ACK packets to specified ports. RST response means host is alive.

How it works: This is weird. ACK is normally the third step in TCP handshake, acknowledging a SYN+ACK. Sending an unsolicited ACK is abnormal. A live host's TCP stack will respond with RST (reset) because there's no established connection to acknowledge. Dead host? Silence or ICMP unreachable.

Why this exists: Stateless firewalls. Some firewalls allow ACK packets inbound because they look like part of an established connection (outbound request, inbound ACK). They block unsolicited SYNs (new connections) but let ACKs through. This is naive filtering but it exists in the wild.

When to use: When you suspect stateless or poorly configured firewalls that allow ACK but block SYN. Not common in modern networks with stateful inspection, but legacy networks still have this. Also useful when SYN probes are being logged or filtered but ACKs aren't.

The difference: TCP SYN looks like a new connection attempt (flagged by IDS). TCP ACK looks like part of existing traffic (might slip through). Different filtering, different detection signatures.

UDP Ping

nmap -sn -PU53,161 <target>

What it does: Sends UDP packets to specified ports (default high ports if not specified). ICMP Port Unreachable = alive. Any UDP response = alive. Silence = probably filtered or open.

How it works: UDP is connectionless, no handshake. Send a UDP packet to a port. If the port is closed, the host's IP stack returns ICMP Port Unreachable (type 3, code 3). That ICMP error tells you the host is up. If the port is open and the service responds with UDP, also alive. No response? Could be filtered, could be open but silent, could be dead.

When to use: When TCP and ICMP are both filtered but UDP services (DNS port 53, SNMP port 161) are available. Some networks filter TCP SYN floods aggressively but are permissive with UDP because they run DNS or SNMP. Probe those ports, get ICMP errors back, confirm host is alive.

The catch: UDP is unreliable. No response doesn't definitively mean dead - might just be rate-limited ICMP, might be open port that doesn't respond to garbage data. Less reliable than TCP or ICMP Echo but useful when those are blocked.

Example scenario: Network filtering TCP SYN probes but running DNS servers on port 53. UDP probe to 53 gets ICMP Port Unreachable from non-DNS hosts (alive), or actual DNS response from DNS servers (also alive).

IP Protocol Ping

nmap -sn -PO <target>

What it does: Sends packets using multiple IP protocols (ICMP, IGMP, TCP, UDP, etc. - raw IP headers with different protocol numbers). Any response from any protocol means host is alive.

How it works: IP packets have a protocol field in the header (protocol 1 = ICMP, 6 = TCP, 17 = UDP, etc.). Nmap sends packets with various protocol numbers. If the host responds to any of them - or returns ICMP Protocol Unreachable for unsupported protocols - you know it's alive.

When to use: When everything else is filtered. Some networks filter ICMP, TCP, UDP at application-aware firewalls but don't filter less common IP protocols (IGMP, GRE, etc.). This is a last-resort probe when standard methods fail. Also useful for finding routers or specialized network equipment that might respond to routing protocols.

Reality check: Most modern firewalls block or ignore unusual IP protocols. This is situational - works on networks with simplistic filtering rules but rarely effective on hardened networks. More of a "let's try everything" approach.

Legacy ICMP Types

nmap -sn -PM <target>  # Address Mask Request
nmap -sn -PP <target>  # Timestamp Request

What they are: Less common ICMP message types. -PM sends ICMP Address Mask Request (type 17), -PP sends ICMP Timestamp Request (type 13). Standard ping is ICMP Echo (type 8).

The unusual types: Most people think "ICMP = ping" (unrelated side note: read ping's source code, it's a fun read) but ICMP has many message types:

  • Type 8: Echo Request (standard ping)
  • Type 13: Timestamp Request (asks for host's current time)
  • Type 17: Address Mask Request (asks for subnet mask - legacy, rarely used)
  • Plus others: Router Advertisement, Router Solicitation, etc.

How it works: Firewalls and IDS often specifically block ICMP Echo (type 8) because that's what ping uses. But they might not block type 13 or 17 because admins forget those exist. Send a Timestamp or Address Mask request, get a response, confirm host is alive.

When to use: When ICMP Echo is explicitly blocked but admins were lazy about blocking all ICMP types. Timestamp requests are occasionally useful because some systems respond with their actual system time (information leak). Address Mask requests are mostly useless on modern networks - legacy feature from when hosts needed to query routers for subnet masks.

Reality check: Hit rate is low. Most modern firewalls either allow all ICMP or block all ICMP. But on networks with specific "block type 8" rules, these can slip through. Worth trying when standard pings fail, but don't expect miracles.

Why So Many Probes?

Because networks are filtered differently. One blocks ICMP, allows TCP. Another blocks TCP SYN, allows ACK. Another rate-limits everything except UDP to DNS.

Nmap gives you options. Start with the reliable ones (ARP on L2, ICMP on routed networks). When those fail, try TCP SYN to common ports. Still nothing? Try ACK, UDP, weird ICMP types. One of them will probably work.

Or the host is actually dead. That's also possible. Insert shrug emoji.

OS Discovery: Fingerprinting the Target

TCP/IP Stack Fingerprinting

nmap -O <target>

What it does: TCP/IP stack fingerprinting to guess remote OS and kernel.

How it works: Nmap sends crafted TCP, UDP and ICMP probes with varying flag combinations, TTLs, options, window sizes, malformed/edge cases. Collects responses - presence/absence, TCP flags, IP ID behavior, DF bit treatment, TTL values, TCP option ordering. Matches observed fingerprint against Nmap's OS database, produces OS guesses with confidence scores. Passive indicators like open ports and service banners combine for higher confidence.

When to use: Fast coarse OS estimate. Reports probable OS family, CPE identifiers, accuracy. Use when you need OS-level context to choose further tests.

The limitation: Heuristic guesses based on network stack behavior. Not always precise.

SMB OS Discovery (Application Layer)

nmap --script smb-os-discovery.nse -p 445 <target>

What it does: Retrieves OS, computer name, domain/workgroup, timing via SMB.

How it works: NSE script uses SMB protocol exchanges (negotiation and infoleaks) to request NetBIOS/SMB peer info and parse server responses. Windows and Samba implementations expose descriptive strings in SMB responses.

When to use: Prefer when SMB is available (ports 139/445 reachable). Yields explicit strings and time-synced info rather than heuristic guesses. Higher confidence than stack fingerprinting.

Comparison: -O is generic network-stack fingerprinting, works without application access. smb-os-discovery uses application layer (requires SMB ports), returns precise hostnames, domain, OS strings, timestamps. Use SMB when you can, -O when you can't.

Port & Service Discovery: The Main Event

TCP SYN Scan (Half-Open)

nmap -sS -p- -T4 -v <target>

What it does: TCP SYN (half-open) scan over all TCP ports with faster timing and verbose output. Reports open/closed/filtered.

How it works: -sS sends SYN probes and classifies by reply:

  • SYN+ACK → port open (Nmap completes with RST to avoid full connection)
  • RST → closed
  • No response or ICMP unreachable → filtered

-p- scans all 65536 ports (0-65535). -T4 adjusts timing (timeouts, parallelism) for speed on reliable networks. -v increases logging verbosity.

Half-open approach reduces chance of application logging and can be faster than full connect. Nmap measures response timing and adapts retries.

When to use: Best default for TCP port enumeration on remote hosts. Efficient and commonly effective against systems that log full connections. Requires raw socket or privileged operation (or npcap on Windows).

Comparison: -sS vs -sT - Full connect (-sT) uses OS TCP stack, completes three-way handshake. Less stealthy, slower, but works without raw privileges. Use -sT when -sS unavailable.

TCP Connect Scan (Full Handshake)

nmap -sT -p 22,80,443 -v <target>

What it does: Full TCP connect scan on specified ports.

How it works: Uses OS API to open TCP connections. TCP stack completes handshakes, Nmap interprets success/failure. Simpler to run non-privileged but more visible in target logs.

When to use: Raw sockets unavailable (non-root), or when you need TCP handshake semantics identical to normal client connections (testing IDS behavior).

Half-Open vs Full Connect: The Real Difference

Let's break down what actually happens at the packet level, because this matters.

Full Connect Scan (-sT): The Complete Handshake

The three-way handshake:

  1. Scanner → Target: SYN (synchronize, let's connect)
  2. Target → Scanner: SYN+ACK (synchronized, acknowledged, I'm ready)
  3. Scanner → Target: ACK (acknowledged, connection established)
  4. Scanner → Target: RST or FIN (close connection immediately)

This is a complete TCP connection. Your OS TCP stack handles it using the standard connect() system call, same as any normal application opening a socket. The connection is fully established, then immediately torn down.

What gets logged: The target application sees a full connection attempt. Web servers log it in access logs. SSH logs connection attempts. Any application-level logging will record this as a real connection because, well, for crying out loud, it is a real connection. The fact that it closes immediately doesn't matter - it completed the handshake. That makes it a real connection.

Performance: Slower. You're waiting for the full three-way handshake plus teardown. Your OS manages connection state, buffers, timers. Every port scan creates actual TCP state on both machines.

Privileges: Works without root/admin. Uses normal OS sockets API. Any user can do this.

Half-Open Scan (-sS): The Stealth Approach

The incomplete handshake:

  1. Scanner → Target: SYN (synchronize, let's connect)
  2. Target → Scanner: SYN+ACK (synchronized, acknowledged, I'm ready)
  3. Scanner → Target: RST (reset, nevermind, forget this ever happened)

Connection never completes. You send SYN, get SYN+ACK back (confirming port is open), then immediately send RST to abort before the connection is established. No ACK, no connection state, no completion.

Why it's called "half-open": You've opened half of the connection (sent SYN, got SYN+ACK) but never completed it (never sent final ACK). The target was ready to accept your connection but you bailed before finishing. There's a joke in there somewhere.

What gets logged: This is where it gets interesting. Many applications log at the connection-established phase (after the full three-way handshake). If you abort with RST before sending ACK, many applications never see it. It doesn't reach the application layer - the TCP stack handles SYN+ACK and expects ACK next, but gets RST instead.

Some systems do log SYN attempts (SYN flood protection, IDS). But basic application logs (Apache access logs, SSH connection logs) often miss these because the connection never completed.

Performance: Faster. You only wait for SYN and SYN+ACK. No connection state maintained in your OS (you're crafting raw packets, bypassing normal TCP stack). Can scan thousands of ports quickly because you're not burdened with actual connection management.

Privileges: Requires raw socket access. On Linux/Unix that means root. On Windows, requires admin and Npcap. You're crafting raw IP/TCP packets, not using OS socket API.

The Detection and Stealth Factor

Full connect is obvious:

  • Shows up in application logs as connection attempts
  • IDS sees complete TCP handshake patterns
  • Firewall logs record established connections
  • Easy to correlate and identify scanning behavior

Half-open is less obvious:

  • May not reach application logging (depends on implementation)
  • IDS still sees SYN patterns (many IDS specifically watch for SYN scans)
  • Fewer logs on the target means less forensic trail
  • Faster scanning makes it harder to react in real-time

But here's the reality: modern IDS/IPS systems flag both. Half-open isn't "stealth" in the sense of being undetectable - it's "stealth" in the sense of being harder to log at the application level. Network-level monitoring will catch both. In my experience, serious companies use modern, well-configured monitoring tools, which will reliably catch you, since most people attempting these scans are script kiddies.

When the Difference Matters

Use full connect (-sT) when:

  • You don't have root/admin (can't use raw sockets)
  • You're testing how applications respond to real connections
  • You're on a network that drops/messes with raw packets
  • You want scanning behavior identical to normal client connections

Use half-open (-sS) when:

  • You have root/admin privileges
  • You want faster scanning (thousands of ports)
  • You want to minimize application-level logs
  • You're doing large-scale reconnaissance where speed matters

Bottom line: Half-open is faster and leaves less application-layer trail. Full connect always works but is slower and noisier. Both are detectable by network monitoring. Choose based on your privileges and goals, not on magical "stealth" properties.

UDP Scan (The Slow One)

nmap -sU -p 53,161 -v <target>

What it does: UDP scan for services on specified ports.

How it works: Sends UDP datagrams to target ports. Interprets ICMP Port Unreachable as closed. No reply often means open|filtered (UDP has no handshake). Nmap may send payloads appropriate to common services (DNS, SNMP) to provoke responses.

UDP scanning is inherently slower due to retransmission timeouts and ICMP rate-limiting.

When to use: UDP services (DNS, SNMP, NTP, syslog) are common attack surfaces. -sU required to find them. Expect longer runtimes and false negatives without service-specific payloads.

Pro tip: Combine with -sV for version detection on discovered UDP ports.

Service/Version Detection

nmap -sV -sS -p <ports> --version-intensity 5 <target>

What it does: Service/version detection for identified ports.

How it works: -sV sends protocol-specific payloads and banner grabs to elicit service responses. Matches responses to Nmap's version database signatures. --version-intensity adjusts probe depth (higher = more probes, more noise). Combining with -sS does TCP SYN port discovery and, where open, active probing for version strings.

When to use: Knowing service versions is critical for vulnerability identification and prioritization. Use conservative intensity in sensitive environments.

Aggressive Scan (The Noisy One)

nmap -A <target>

What it does: Aggressive scan - runs -O, -sV, default NSE scripts (-sC), and traceroute.

How it works: Bundles multiple active probes for comprehensive recon: OS fingerprinting, version detection, common script checks (vuln/info scripts), path mapping. Generates significant noise, easily flagged by IDS.

When to use: Quick, broad reconnaissance when permission and stealth aren't concerns. Not suitable for stealth or minimal footprint scenarios.

Specialized Scans (Mostly Academic)

Xmas scan (-sX): Manipulates FIN/URG/PSH flags. Relies on differing TCP/IP stack responses per RFC idiosyncrasy. Many modern stacks and firewalls neutralize or normalize these responses. Unreliable on modern targets.

Null (-sN) / FIN (-sF): Similar to Xmas, different flags. Use only for conceptual understanding. Unreliable on networks with modern TCP/IP stacks and middleboxes.

ACK scan (-sA): Maps firewall rulesets (stateful filter detection). ACK probe elicits RST from unfiltered hosts, no response or ICMP from filtered. Doesn't reveal open ports, just firewall behavior.

Idle scan (-sI): Uses third-party "zombie" host's IP ID sequence to perform blind scans that hide scanner's IP. Highly situational and complex. Requires predictable IP ID on zombie. Noisy if prerequisites fail.

Scanning Beyond Firewalls: Evasion Techniques

Important: These are detection-avoidance techniques. They alter packet appearance, timing, or source attribution. Increase likelihood of evading naive IDS/signatures but also increase complexity, unpredictability, and legal risk. Use only with authorization.

Packet Fragmentation

nmap -f <target>

What it does: Fragment probe packets into smaller IP fragments.

How it works: -f sets DF bit off, instructs Nmap to fragment packets so signature matchers inspecting per-packet payloads may miss full probe patterns. Some IDS/IPS reassemble fragments but many lightweight filters don't. Fragmentation forces target stack to reassemble before TCP/IP processing.

When to use: Attempt to evade simple stateless packet filters or signature engines that don't reassemble. Effectiveness varies widely. Fragmentation can break probes and cause different responses. Many modern devices discard fragments or reassemble for inspection.

MTU Control

nmap --mtu <size> <target>

What it does: Lower MTU and send smaller fragments.

How it works: Controls raw packet sizes. Small MTU can force fragmentation on path. Similar effects to -f but gives explicit control of fragment payload sizes. Network devices may normalize or drop such traffic.

Source Port Manipulation

nmap -g 80 <target>
# or
nmap --source-port 80 <target>

What it does: Set source port to privileged/well-known port to exploit permissive ACLs.

How it works: Some ACLs permit inbound traffic from trusted ports (HTTP 80, DNS 53). Spoofing source port can make probes appear to originate from allowed services. Source-port manipulation doesn't change payload or TCP flags. Many modern firewalls perform stateful inspection and will still block unsolicited SYNs without proper state.

When to use: When you suspect ACLs allow traffic from specific source ports. Not effective against stateful firewalls.

Decoy Scanning

nmap -D RND:10 <target>

What it does: Use decoy IPs to obfuscate true scan origin by interleaving probe packets with those from multiple IPs.

How it works: Nmap crafts packets that appear sourced from listed decoy IPs plus real scanner. Target logs show probes from all addresses. Locating true scanner requires correlation (real IP position among decoys is randomized). Decoying is detectable by correlation and can trigger alarms for spoofed traffic. Requires ability to spoof source IPs (raw sockets). Many networks drop spoofed packets or use ingress filtering (BCP38).

When to use: Add ambiguity to logs. Effectiveness depends on target network controls and logging correlation capabilities.

MAC Spoofing + Skip Host Discovery

nmap -sT -Pn --spoof-mac 0 <target>

What it does: -Pn skips host discovery (treats hosts as up), --spoof-mac 0 randomizes MAC.

How it works: -Pn forces Nmap to attempt scanning without pre-checking for host liveness (useful when ICMP/TCP pings are blocked). --spoof-mac 0 selects random MAC or vendor-prefixed MAC, masking hardware identity on L2. MAC spoofing only works on L2 segments where you control interface. Switched networks and network access controls may block unknown MACs or require 802.1X. -sT logs full connections on scanner's host.

When to use: Bypassing host discovery filters and obfuscating NIC fingerprinting on local networks. Not effective across routed links where MACs aren't visible.

Reality Check on Evasion

Timing matters: -T0 through -T5 profoundly affect detectability. -T0/T1 are slow (stealthier), -T4/T5 are noisy but faster. IDS evasion often requires slow, randomized timing, not single aggressive commands.

Modern networks: Evasion flags that rely on IP/MAC spoofing, decoys, source-port manipulation assume lack of ingress/egress filtering (BCP38) and permissive logging. Modern networks frequently negate these assumptions.

Anomaly detection: Fragmentation, malformed packets, obscure TCP flag combinations can trigger anomaly detection and may cause probes to be dropped or mis-reassembled. False positives/negatives.

Arms race: Many IDS/IPS systems and endpoint agents are tuned to detect Nmap signatures and NSE script behavior. Techniques that worked historically are less reliable today. Evasion is an arms race.

Practical Recommendations

Local host discovery: Use -sn -PR for accurate results. ARP can't be filtered on L2.

Routed host discovery: Fall back to -PE, -PS, -PU depending on expected service responses.

TCP port discovery: Use -sS -p- -T4 as default on remote hosts. Fall back to -sT if unprivileged. Combine -sV when you need service/version context.

UDP discovery: Use -sU thoughtfully. Add service-specific probes for better detection. Expect slower scans.

OS fingerprinting: Use -O plus application-level scripts (SMB, HTTP headers) to increase confidence.

Aggressive scanning: Avoid -A and aggressive evasion in operational contexts without explicit authorization. High noise, high legal risk.

Million Dollar Question: How Do You Remember All These Commands!?

Yes.

Host discovery:

  • SN-sn : skip port scan (host-only).
  • AP-PR : ARP probe (local, reliable).
  • PE-PE : ICMP echo (classic ping).
  • PU-PU : UDP ping.
  • PS-PS : TCP SYN ping.
  • PA-PA : TCP ACK ping.
  • PO-PO : IP-protocol ping.

OS discovery:

  • O-O : OS fingerprinting (stack probes).
  • SMB--script smb-os-discovery.nse -p 139,445 : application-level OS info.

Port & service discovery:

  • SYN-sS : SYN (half-open) scan.
  • T-sT : TCP connect (no raw socket).
  • U-sU : UDP scan.
  • V-sV : version detection.
  • A-A : aggressive bundle (-O, -sV, -sC, traceroute).

Evasion & obfuscation:

  • FRAG-f / --mtu <n> : fragment packets.
  • SRC-g <port> / --source-port : spoof source port.
  • DECOY-D <decoy,...> : decoy IPs.
  • MAC--spoof-mac <addr|0|vendor> : spoof MAC.
  • PN-Pn : skip host discovery (treat hosts as up).

Timing & stealth:

  • -T0/-T1 = slow/stealth, -T4/-T5 = fast/noisy. Memory: Lower T for stealth, higher T for speed.
  • SNAP = host discovery flags, O = OS, SYN = port scans + versions, FRAG = evasion flags, T = timing (-T0..-T5).

The Bottom Line

NMAP is powerful but noisy. Know what each flag does under the hood. Understand when to use TCP SYN vs full connect, when ARP beats ICMP, when evasion techniques actually work (spoiler: less often than you think).

Scanning without authorization is illegal. Get permission. Document your scans. Stay legal.

End of article