Information Security 11 min read

Using nmap4j in Java to Scan Services and Retrieve Database Version Information

This article explains how to integrate the nmap4j library into a Java SpringBoot project to perform Nmap scans for service and version detection, retrieve database details, handle both Windows and Linux environments, and process the XML results with Dom4j, providing complete code examples and parameter guidance.

Selected Java Interview Questions
Selected Java Interview Questions
Selected Java Interview Questions
Using nmap4j in Java to Scan Services and Retrieve Database Version Information

Introduction

When a requirement arose to obtain service information (such as MySQL or Oracle version) based on an IP and port, the author recorded a solution using Java because the native Python module is unavailable in Java.

nmap4j Overview

nmap4j is a Java wrapper for the Nmap port scanner, allowing developers to invoke Nmap functions directly from Java code. The Nmap executable must be installed beforehand (download from https://nmap.org/download.html#windows for Windows or the appropriate Linux package).

Code Explanation

The test code resides in test/org/nmap4j/Nmap4jTest.java . A key snippet shows how to configure Nmap flags, include hosts, execute the scan, and handle errors.

public class Nmap4jTest {
    @Test
    public void basicNmap4jUsageTest() {
        try {
            // Path to Nmap installation
            String path = "/usr/local";
            Nmap4j nmap4j = new Nmap4j(path);
            nmap4j.addFlags("-sV -T5 -O -oX -");
            nmap4j.includeHosts("localhost");
            nmap4j.execute();
            if (!nmap4j.hasError()) {
                NMapRun nmapRun = nmap4j.getResult();
                String output = nmap4j.getOutput();
                if (output == null) { fail(); }
                String errors = nmap4j.getExecutionResults().getErrors();
                if (errors == null) { fail(); }
            }
        } catch (NMapInitializationException e) {
            e.printStackTrace();
            fail();
        } catch (NMapExecutionException e) {
            e.printStackTrace();
            fail();
        }
    }
}

Parameter Description

Common Nmap options are listed, such as target selection ( -iL , -iR , --exclude ), scan types ( -sS , -sT , -sU , -sF , -sX , -sN ), port specification ( -p , --top-ports , -F ), service detection ( -sV , --version-intensity ), OS detection ( -O , --osscan-limit , --osscan-guess ), and output formats ( -oN , -oX , -oG , -oA , -v ).

Implementation in SpringBoot

The author provides a controller method querydb that builds a port string, sets the Nmap path, runs the scan asynchronously, and parses the resulting XML with Dom4j to extract product and version attributes.

/**
 * Use nmap4j to scan
 * @param ip target ip
 * @param ports target ports
 * @return list of port info
 */
@RequestMapping("/querydb")
public List
querydb(@RequestParam("ip") String ip, @RequestParam("ports") List
ports) {
    ArrayList
portInfos = new ArrayList<>();
    String portStr = StrUtil.join(",", ports);
    String path = "D:/StudyApps/nmap";
    String fileName = "temp_result.xml";
    Nmap4j nmap4j = new Nmap4j(path);
    CompletableFuture
future = CompletableFuture.runAsync(() -> {
        nmap4j.addFlags("-sV -p " + portStr + " -T5 -O -oX " + fileName);
        nmap4j.includeHosts(ip);
        try { nmap4j.execute(); } catch (Exception e) { throw new RuntimeException(e); }
    }, threadPoolExecutor);
    future.join();
    return getPortInfo(portInfos, fileName);
}

The helper method getPortInfo reads the temporary XML file, extracts product and version attributes from each <service> element, creates NmapPortInfo objects, and deletes the temporary file.

private List
getPortInfo(List
portInfos, String fileName) {
    String projectPath = System.getProperty("user.dir");
    String filePath = projectPath + FileUtil.FILE_SEPARATOR + fileName;
    log.info("File path: {}", filePath);
    SAXReader reader = new SAXReader();
    Document document = reader.read(FileUtil.file(filePath));
    Element host = document.getRootElement().element("host");
    Element ports = host.element("ports");
    for (Element port : ports.elements("port")) {
        Element service = port.element("service");
        String product = service.attributeValue("product");
        String version = service.attributeValue("version");
        portInfos.add(new NmapPortInfo(product, version));
    }
    FileUtil.del(filePath);
    return portInfos;
}

Linux Adaptation

Because production environments often run on Linux, the author adds a linuxQuerydb method that builds the full Nmap command string and executes it via Runtime.getRuntime().exec , then reuses the same XML parsing logic.

@GetMapping("/linux/querydb")
@SneakyThrows
public List
linuxQuerydb(@RequestParam("ip") String ip, @RequestParam("ports") List
ports) {
    // Build command and run asynchronously similar to the Windows version
    // ... (code omitted for brevity)
    return getPortInfo(portInfos, fileName);
}

Conclusion

The article notes that nmap4j is not available in Maven Central and must be added via a downloaded JAR from https://master.dl.sourceforge.net/project/nmap4j/1.1.0/org.nmap4j-1.1.0-RELEASE.zip . The provided code enables backend services to programmatically obtain database version information through Nmap scans.

BackendJavaInformation Securitynetwork scanningnmap4jservice detection
Selected Java Interview Questions
Written by

Selected Java Interview Questions

A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.