Search code examples
pythonsocketsnmap

Why Python-Nmap cannot scan Localhost but Socket can do it?


This is my script and my question is Why Socket scan the Localhost but Nmap can't?

import nmap
import optparse
import socket

tgtHost = "127.0.0.1"
tgtPort = 80

nmScan = nmap.PortScanner()
try:
    result = nmScan.scan(tgtHost, str(tgtPort))
    nmScan.scan(tgtHost, tgtPort)
    state=nmScan[tgtHost]['tcp'][int(tgtPort)]['state']
    print(" [*] " + tgtHost + " tcp/"+tgtPort +" "+state)
except:
    print(f"{tgtHost} is unreachable.")

try:
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.settimeout(0.5)
        s.connect((tgtHost, tgtPort))
        print(f"Port {tgtPort} is open on {tgtHost}.")

except:
    print(f"{tgtHost} is unreachable.") 

This is the result.

enter image description here


Solution

  • Use this method to check if a port is open or closed :

    import nmap
    
    tgtHost = "127.0.0.1"
    tgtPort = 80
    
    nmScan = nmap.PortScanner()
    
    try:
        result = nmScan.scan(tgtHost, str(tgtPort))
        state = result['scan'][tgtHost]['tcp'][tgtPort]['state']
        print(f"[*] {tgtHost} tcp/{tgtPort} {state}")
    except:
        print(f"{tgtHost} is unreachable.")
    

    Output:

    [*] 127.0.0.1 tcp/80 closed
    

    Another example:

    Example of output