W Kenny
W Kenny

Reputation: 2069

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

Upvotes: 0

Views: 274

Answers (2)

xio
xio

Reputation: 640

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

Upvotes: 1

jurez
jurez

Reputation: 4657

Probably you are doing a ping scan with nmap and ping is closed.

Use equivalent of -Pn switch (or -P0).

Also, check if result of s.connect() is actually a valid connection.

Upvotes: 1

Related Questions