Commit 0bb04bc4 authored by mohammad.salama's avatar mohammad.salama

Version 1

parents
<component name="libraryTable">
<library name="lib">
<CLASSES>
<root url="jar://$PROJECT_DIR$/lib/hamcrest-core-1.3.jar!/" />
<root url="jar://$PROJECT_DIR$/lib/junit-4.12.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="17" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/JavaPortScanner-master.iml" filepath="$PROJECT_DIR$/JavaPortScanner-master.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Palette2">
<group name="Swing">
<item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" />
</item>
<item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" />
</item>
<item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.svg" removable="false" auto-create-binding="false" can-attach-label="true">
<default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" />
</item>
<item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" />
<initial-values>
<property name="text" value="Button" />
</initial-values>
</item>
<item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="RadioButton" />
</initial-values>
</item>
<item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="CheckBox" />
</initial-values>
</item>
<item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" />
<initial-values>
<property name="text" value="Label" />
</initial-values>
</item>
<item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" />
</item>
<item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" />
</item>
<item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1">
<preferred-size width="-1" height="20" />
</default-constraints>
</item>
<item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" />
</item>
<item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" />
</item>
</group>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ChangeListManager">
<list default="true" id="bc0e4876-bdca-4575-8e2f-e6d1b5942353" name="Changes" comment="" />
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="FileTemplateManagerImpl">
<option name="RECENT_TEMPLATES">
<list>
<option value="Class" />
</list>
</option>
</component>
<component name="MarkdownSettingsMigration">
<option name="stateVersion" value="1" />
</component>
<component name="ProjectId" id="2Y3eB8NBMELXwFwVgbjdkQaMbzB" />
<component name="ProjectViewState">
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent">{
&quot;keyToString&quot;: {
&quot;RunOnceActivity.OpenProjectViewOnStart&quot;: &quot;true&quot;,
&quot;RunOnceActivity.ShowReadmeOnStart&quot;: &quot;true&quot;
}
}</component>
<component name="RunManager">
<configuration name="Driver" type="Application" factoryName="Application" temporary="true" nameIsGenerated="true">
<option name="MAIN_CLASS_NAME" value="driver.Driver" />
<module name="JavaPortScanner-master" />
<extension name="coverage">
<pattern>
<option name="PATTERN" value="driver.*" />
<option name="ENABLED" value="true" />
</pattern>
</extension>
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
<configuration name="IPv4IteratorTest.MAIN" type="JUnit" factoryName="JUnit" temporary="true" nameIsGenerated="true">
<module name="JavaPortScanner-master" />
<extension name="coverage">
<pattern>
<option name="PATTERN" value="test.*" />
<option name="ENABLED" value="true" />
</pattern>
</extension>
<option name="PACKAGE_NAME" value="test" />
<option name="MAIN_CLASS_NAME" value="test.IPv4IteratorTest" />
<option name="METHOD_NAME" value="MAIN" />
<option name="TEST_OBJECT" value="method" />
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
<configuration name="ParserTest.MAIN" type="JUnit" factoryName="JUnit" temporary="true" nameIsGenerated="true">
<module name="JavaPortScanner-master" />
<extension name="coverage">
<pattern>
<option name="PATTERN" value="test.*" />
<option name="ENABLED" value="true" />
</pattern>
</extension>
<option name="PACKAGE_NAME" value="test" />
<option name="MAIN_CLASS_NAME" value="test.ParserTest" />
<option name="METHOD_NAME" value="MAIN" />
<option name="TEST_OBJECT" value="method" />
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
<recent_temporary>
<list>
<item itemvalue="JUnit.IPv4IteratorTest.MAIN" />
<item itemvalue="JUnit.ParserTest.MAIN" />
<item itemvalue="Application.Driver" />
</list>
</recent_temporary>
</component>
<component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<changelist id="bc0e4876-bdca-4575-8e2f-e6d1b5942353" name="Changes" comment="" />
<created>1699758554187</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1699758554187</updated>
</task>
<servers />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="lib" level="project" />
</component>
</module>
\ No newline at end of file
# Java Port Scanner
Simple port scanner written in Java with parallelization support.
## Usage
`$ java -jar JavaPortScanner.jar <IPv4> [PortStart-PortEnd]`
- `<IPv4>` is a required parameter that is a valid IPv4 address
- `[PortStart-PortEnd]` is an optional parameter to indicate certain range of ports to scan
- If this is empty, scanner will try to scan all possible ports (can take a long time)
- `PortStart-PortEnd` will scan from `PortStart` to `PortEnd`
## Examples
### Scanning all possible ports
```bash
$ java -jar JavaPortScanner.jar 127.0.0.1
Scanning 127.0.0.1:1-65535
2/65535 were open
80: open
443: open
```
### Scanning certain port(s) only
```bash
$ java -jar JavaPortScanner.jar 127.0.0.1 80
Scanning 127.0.0.1:80
1/1 were open
80: open
$ java -jar JavaPortScanner.jar 127.0.0.1 80-81
Scanning 127.0.0.1:80-81
1/2 were open
80: open
```
package driver;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import scanner.PortScanner;
import scanner.PortScannerResult;
import scanner.PortStatus;
/**
* USAGE: JavaPortScanner [target IP] [IP Last Target] [port range]
* <ul>
* <li>[target IP]: IP address start to scan</li>
* <li>[port range]: range of ports to scan</li>
* <ul>
* <li>e.g. 80-100 scans from 80 to 100</li>
* <li>e.g. 8080 scans only port 8080</li>
* </ul>
* </ul>
*/
public class Driver {
private static final int SCAN_TIMEOUT = 200;
private static final int THREAD_COUNT = 128;
public static void main(String[] args) {
// get a Target info from Parser
List<Target> targets = new ArrayList<>();
String[] Args = new String[3];
Args[0] = "8.8.8.4";
Args[1] = "8.8.8.9";
Args[2] = "19-80";
try {
targets = Parser.run(Args);
} catch (InvalidUserInputException e) {
// exit with the message
System.err.println(e.getMessage());
System.exit(1);
}
// run a scan on the target and get a result
for (Target t : targets)
{
SingleIPDriver.start(t);
}
}
}
package driver;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;
public class IPv4Iterator
{
public static List<String> iterateIPv4Addresses(String startIP, String endIP) throws UnknownHostException
{
InetAddress start = InetAddress.getByName(startIP);
InetAddress end = InetAddress.getByName(endIP);
byte[] startAddress = start.getAddress();
byte[] endAddress = end.getAddress();
long startValue = bytesToLong(startAddress);
long endValue = bytesToLong(endAddress);
List<String> ipAddresses = new ArrayList<>();
for (long i = startValue; i <= endValue; i++) {
InetAddress address;
try {
address = InetAddress.getByAddress(longToBytes(i));
ipAddresses.add(address.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
return ipAddresses;
}
public static long bytesToLong(byte[] bytes) {
long result = 0;
for (byte b : bytes) {
result = result << 8 | (b & 0xFF);
}
return result;
}
public static byte[] longToBytes(long value) {
byte[] bytes = new byte[4];
for (int i = 3; i >= 0; i--) {
bytes[i] = (byte) (value & 0xFF);
value >>= 8;
}
return bytes;
}
}
\ No newline at end of file
package driver;
public final class InvalidUserInputException extends Exception {
/**
* IDE-generated serialVersionUID to suppress the warning.
*/
private static final long serialVersionUID = -3383457683260998220L;
/**
* Indicates which user-provided fields are invalid. Possible options are
* "ip", "port", or "both".
*/
private String invalidInputField;
/**
* Constructor for InvalidUserInputException. Parameter 'field' must be
* either "ip", "port", or "default" to indicate which inputs are invalid.
*
* @param field indicate which user-inputs are invalid
*/
public InvalidUserInputException(String field) {
if ((field.equals("ip") || field.equals("port")
|| field.equals("both"))) {
this.invalidInputField = field;
} else {
// set to "default" when field is non-acceptable
this.invalidInputField = "default";
}
}
@Override
public String getMessage() {
// generic default message
String ret = "Invalid user input";
if (!this.invalidInputField.equals("default")) {
// more specific message
ret += ": " + this.invalidInputField;
}
return ret;
}
}
package driver;
import scanner.IPHandler;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
public final class Parser {
/**
* Get target information from user inputs.
*
* @param args arguments from user
*/
public static List<Target> run(String[] args) throws InvalidUserInputException
{
List<Target> ret = new ArrayList<>();
List<String> IPs = new ArrayList<>();
if (args.length < 2 || args.length >3)
{
throw new InvalidUserInputException("default");
}
// set ip
if (isValidIPv4Address(args[0]) && isValidIPv4Address(args[1]))
{
try
{
IPHandler ipHandler = new IPHandler(args[0] , args[1]);
String startIP = ipHandler.getStartIP();
String endIP = ipHandler.getEndIP();
IPs = IPv4Iterator.iterateIPv4Addresses(startIP , endIP);
for (String ip : IPs)
{
Target target = new Target();
target.targetIP = ip;
ret.add(target);
}
}
catch (IPHandler.IPExeption e)
{
throw new RuntimeException(e);
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
} else {
// invalid ip
throw new InvalidUserInputException("ip");
}
// set port range
String targetPortStart;
String targetPortEnd;
if (args.length == 2) {
// target all possible port if provided ip is valid
targetPortStart = "1";
targetPortEnd = "65535";
} else if (args[2].contains("-")) {
// is a range
// first occurrence of dash
int index = args[2].indexOf("-");
targetPortStart = args[2].substring(0, index);
targetPortEnd = args[2].substring(index + 1, args[2].length());
} else {
// a single port
targetPortStart = args[2];
targetPortEnd = args[2];
}
try {
int p1 = Integer.parseInt(targetPortStart);
int p2 = Integer.parseInt(targetPortEnd);
for (Target target : ret)
{
target.portRange[0] = p1;
target.portRange[1] = p2;
}
} catch (Exception e)
{
// could not convert port num to int
throw new InvalidUserInputException("port");
}
// check if ports are in valid range
for (int i=0 ; i<ret.size(); i++)
{
if (!isValidPortNumber(ret.get(i).portRange[0]) || !isValidPortNumber(ret.get(i).portRange[1]))
{
throw new InvalidUserInputException("port");
}
}
return ret;
}
/**
* Return true iff portNum is in valid range, 1 to 65535.
*
* @param portNum port number to check.
* @return whether portNum is a valid port number.
*/
private static boolean isValidPortNumber(int portNum) {
return (1 <= portNum && portNum <= 65535);
}
/**
* Validate provided IPv4 address.
*
* @param ip
* @return whether ip is a valid IPv4 Address
*/
private static boolean isValidIPv4Address(String ip) {
try {
return InetAddress.getByName(ip).getHostAddress().equals(ip);
} catch (UnknownHostException e) {
return false;
}
}
}
package driver;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import scanner.PortScanner;
import scanner.PortScannerResult;
import scanner.PortStatus;
public class SingleIPDriver
{
private static final int SCAN_TIMEOUT = 200;
private static final int THREAD_COUNT = 8;
public static void start(Target t)
{
// run a scan on the target and get a result
System.out.println("Scanning " + t.targetIP + ":" + t.portRange[0] + "-" + t.portRange[1]);
// lists to populate
List<Future<PortStatus>> futureList = new ArrayList<>();
List<PortStatus> resultList = new ArrayList<>();
// ExecutorService
ExecutorService es = Executors.newFixedThreadPool(THREAD_COUNT);
// loop through provided port range
for (int currPort = t.portRange[0]; currPort <= t.portRange[1]; currPort++) {
futureList.add(PortScanner.isPortOpen(es, t.targetIP, currPort, SCAN_TIMEOUT));
}
es.shutdown();
try {
if (!es.awaitTermination(2, TimeUnit.MINUTES)) {
// timeout elapsed before termination
es.shutdownNow();
}
} catch (InterruptedException e) {
es.shutdownNow();
}
// get results to resultList
for (Future<PortStatus> eachFuture : futureList) {
try {
resultList.add(eachFuture.get(2, TimeUnit.MINUTES));
} catch (Exception e) {
System.err.println("Timeout reached");
System.exit(1);
}
}
// display results
PortScannerResult r = new PortScannerResult(resultList);
System.out.println(r);
}
}
package driver;
public final class Target {
public String targetIP;
public int[] portRange;
public Target() {
portRange = new int[2];
}
}
package scanner;
import java.security.UnresolvedPermission;
import java.util.ArrayList;
import java.util.List;
public class IPHandler
{
private String StartIP;
private String EndIP;
public IPHandler(String fip , String eip) throws IPExeption
{
this.StartIP = minIP(fip,eip);
this.EndIP = maxIP(fip , eip);
}
private String maxIP(String fip , String eip)
{
int[] ip1,ip2 = new int[4];
ip1 = convertIPtoIntegers(fip);
ip2 = convertIPtoIntegers(eip);
for (int i=0 ; i<4 ; i++)
{
if (ip1[i] > ip2[i]) return fip;
if (ip1[i] < ip2[i]) return eip;
}
return fip;
}
private String minIP(String fip , String eip)
{
if (maxIP(fip,eip).equals(fip)) return eip;
return fip;
}
private int[] convertIPtoIntegers(String ip)
{
int[] ip1 = new int[4];
String[] parts = ip.split("\\.");
for (int i = 0; i < 4; i++)
{
ip1[i] = Integer.parseInt(parts[i]);
}
return ip1;
}
public static class IPExeption extends Exception
{
String Error = "Invalid Range";
public IPExeption ()
{
System.out.println(Error);
}
}
public String getStartIP()
{
return StartIP;
}
public String getEndIP()
{
return EndIP;
}
public List<String> iterateIPRange()
{
List<String> ans = new ArrayList<>();
int[] fip = new int[4];
fip = convertIPtoIntegers(this.StartIP);
int[] eip = new int[4];
eip = convertIPtoIntegers(this.EndIP);
return ans;
}
}
package scanner;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
public final class PortScanner {
public static Future<PortStatus> isPortOpen
(ExecutorService es, String ip, int port, int timeout)
{
return es.submit( ()-> {
{
boolean stat;
try (Socket sfd = new Socket()) {
sfd.connect(new InetSocketAddress(ip, port), timeout);
// connection ok
// r.getOpenList().add(port);
stat = true;
} catch (Exception e) {
// connection failed
// r.getCloseList().add(port);
stat = false;
}
return new PortStatus(port, stat);
}
});
}
}
package scanner;
import java.util.ArrayList;
import java.util.List;
public final class PortScannerResult {
private List<PortStatus> openList;
private List<PortStatus> closedList;
public PortScannerResult(List<PortStatus> resultList) {
this.openList = new ArrayList<>();
this.closedList = new ArrayList<>();
for (PortStatus eachPortStatus : resultList) {
if (eachPortStatus.getIsOpen()) {
openList.add(eachPortStatus);
} else {
closedList.add(eachPortStatus);
}
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
int totalCount = openList.size() + closedList.size();
sb.append(openList.size() + "/" + totalCount + " were open\n");
for (PortStatus openPortStatus : openList) {
sb.append(openPortStatus + "\n");
}
return sb.toString();
}
}
package scanner;
public final class PortStatus {
private int portNum;
private boolean isOpen;
public PortStatus(int portNum, boolean isOpen) {
this.portNum = portNum;
this.isOpen = isOpen;
}
public int getPortNum() {
return this.portNum;
}
public boolean getIsOpen() {
return this.isOpen;
}
@Override
public String toString() {
String status = "closed";
if (isOpen) {
status = "open";
}
return portNum + ":\t" + status;
}
}
package test;
import driver.IPv4Iterator;
import org.junit.Test;
import java.net.UnknownHostException;
import java.util.List;
public class IPv4IteratorTest
{
@Test
public void MAIN() throws UnknownHostException {
String ip = "192.168.98.55";
String ip2 = "192.168.99.1";
List<String> list = IPv4Iterator.iterateIPv4Addresses(ip , ip2);
for (String s : list) System.out.println(s);
}
}
package test;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import driver.IPv4Iterator;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import driver.InvalidUserInputException;
import driver.Parser;
import driver.Target;
public class ParserTest
{
@Test
public void MAIN() throws UnknownHostException {
String ip = "192.168.98.55";
String ip2 = "192.168.99.1";
List<String> list = IPv4Iterator.iterateIPv4Addresses(ip , ip2);
for (String s : list) System.out.println(s);
}
/*
private ArrayList<String> userArgs;
private static final String SAMPLE_IP_ADDR = "123.123.123.123";
private String[] getUserArgs() {
return this.userArgs.toArray(new String[this.userArgs.size()]);
}
private Target getExpectedTarget(String IP, int portStart, int portEnd) {
Target expectedTargetStruct = new Target();
expectedTargetStruct.portRange[0] = portStart;
expectedTargetStruct.portRange[1] = portEnd;
expectedTargetStruct.targetIP = IP;
return expectedTargetStruct;
}
@Rule
public ExpectedException exceptionRule = ExpectedException.none();
@Before
public void setup() {
userArgs = new ArrayList<>();
}
@Test
public void testValidCaseWithPortRange() {
Target exp = getExpectedTarget(SAMPLE_IP_ADDR, 14, 23);
Target act = null;
userArgs.add(SAMPLE_IP_ADDR);
userArgs.add("14-23");
try {
act = Parser.run(getUserArgs());
// assertEquals(exp.portRange, act.portRange);
assertTrue(Arrays.equals(exp.portRange, act.portRange));
assertEquals(exp.targetIP, act.targetIP);
} catch (Exception e) {
fail("Unexpected exception :(");
}
}
@Test
public void testValidCaseWithSinglePort() {
Target exp = getExpectedTarget(SAMPLE_IP_ADDR, 22, 22);
Target act = null;
userArgs.add(SAMPLE_IP_ADDR);
userArgs.add("22");
try {
act = Parser.run(getUserArgs());
assertTrue(Arrays.equals(exp.portRange, act.portRange));
assertEquals(exp.targetIP, act.targetIP);
} catch (Exception e) {
fail("Unexpected exception :(");
}
}
@Test
public void testMissingIPInput() throws InvalidUserInputException {
// expects exception
exceptionRule.expect(InvalidUserInputException.class);
exceptionRule.expectMessage("Invalid user input");
// user only input port range
userArgs.add("14-23");
Parser.run(getUserArgs());
}
@Test
public void testInvalidPortRangeAlphanumericInput() throws InvalidUserInputException {
// expects exception
exceptionRule.expect(InvalidUserInputException.class);
exceptionRule.expectMessage("Invalid user input: port");
// user input alphanumeric port range
userArgs.add(SAMPLE_IP_ADDR);
userArgs.add("24a-d3f");
Parser.run(getUserArgs());
}
@Test
public void testInvalidPortRangeMultipleDashes() throws InvalidUserInputException {
// expects exception too
exceptionRule.expect(InvalidUserInputException.class);
exceptionRule.expectMessage("Invalid user input: port");
// user input multiple dashes for port range
userArgs.add(SAMPLE_IP_ADDR);
userArgs.add("14--15");
Parser.run(getUserArgs());
}
@Test
public void testValidPortRangeAllPorts() {
Target exp = getExpectedTarget(SAMPLE_IP_ADDR, 1, 65535);
Target act = null;
userArgs.add(SAMPLE_IP_ADDR);
try {
act = Parser.run(getUserArgs());
assertArrayEquals(exp.portRange, act.portRange);
assertEquals(exp.targetIP, act.targetIP);
} catch (Exception e) {
fail("Unexpected Exception :O");
}
}*/
}
\ No newline at end of file
package test;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.junit.Before;
import org.junit.Test;
import scanner.PortScanner;
import scanner.PortStatus;
public class PortScannerTest {
private static final int TIMEOUT = 200;
private static final int THREAD_COUNT = 16;
private static final String GOOGLE_IP = "64.233.185.139";
private ExecutorService es;
private List<PortStatus> expected;
private List<PortStatus> actual;
@Before
public void setup() {
es = Executors.newFixedThreadPool(THREAD_COUNT);
expected = new ArrayList<>();
actual = new ArrayList<>();
}
/**
* This simulates how driver will scan but this will return PortScannerResult obj for testing.
*
* @param ip target IP address
* @param portStart start of port range
* @param portEnd end of port range
*/
private void getResults(String ip, int portStart, int portEnd) {
List<Future<PortStatus>> futures = new ArrayList<>();
for (int port = portStart; port <= portEnd; port++) {
futures.add(PortScanner.isPortOpen(es, ip, port, TIMEOUT));
}
es.shutdown();
try {
if (!es.awaitTermination(1, TimeUnit.MINUTES)) {
// timeout elapsed before termination
es.shutdownNow();
}
} catch (InterruptedException e) {
es.shutdownNow();
}
List<PortStatus> resultList = new ArrayList<>();
for (Future<PortStatus> eachFuture : futures) {
try {
resultList.add(eachFuture.get(TIMEOUT, TimeUnit.MILLISECONDS));
} catch (Exception e) {
e.printStackTrace();
}
}
actual = resultList;
}
private void runCompare() {
assertEquals(expected.size(), actual.size());
for (int i = 0; i < expected.size(); i++) {
PortStatus expStatus = expected.get(i);
PortStatus actStatus = actual.get(i);
assertEquals(expStatus.getPortNum(), actStatus.getPortNum());
assertEquals(expStatus.getIsOpen(), actStatus.getIsOpen());
}
}
@Test
public void testScanGoogleSinglePort() {
expected.add(new PortStatus(80, true));
getResults(GOOGLE_IP, 80, 80);
runCompare();
}
@Test
public void testScanGoogleMultiplePorts() {
for (int i = 80; i <= 443; i++) {
expected.add(new PortStatus(i, (i == 80 || i == 443)));
}
getResults(GOOGLE_IP, 80, 443);
runCompare();
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment