Commit 01e3f9fc authored by ali's avatar ali

Initial commit

parents
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" project-jdk-name="1.8 (2)" 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="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="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AutoImportSettings">
<option name="autoReloadType" value="SELECTIVE" />
</component>
<component name="ChangeListManager">
<list default="true" id="00f5bc34-e1f6-4ecf-baf4-26cf412b6ea4" name="Changes" comment="">
<change afterPath="$PROJECT_DIR$/.gitignore" afterDir="false" />
<change afterPath="$PROJECT_DIR$/.idea/encodings.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/.idea/misc.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/.idea/uiDesigner.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/.idea/vcs.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/pom.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/org/example/IPOperations.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/org/example/InvalidUserInputException.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/org/example/Main.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/org/example/Parser.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/org/example/PortScanner.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/org/example/PortScannerResult.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/org/example/PortStatus.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/org/example/Target.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/test/java/org/example/ParserTest.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/test/java/org/example/PortScannerTest.java" afterDir="false" />
</list>
<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="JUnit3 Test Class" />
<option value="Class" />
</list>
</option>
</component>
<component name="Git.Settings">
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
</component>
<component name="MarkdownSettingsMigration">
<option name="stateVersion" value="1" />
</component>
<component name="MavenImportPreferences">
<option name="generalSettings">
<MavenGeneralSettings>
<option name="usePluginRegistry" value="true" />
</MavenGeneralSettings>
</option>
</component>
<component name="ProjectId" id="2YAJDp5eAtWBoNdpPdYXPz5Vt7e" />
<component name="ProjectLevelVcsManager" settingsEditedManually="true" />
<component name="ProjectViewState">
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent"><![CDATA[{
"keyToString": {
"RunOnceActivity.OpenProjectViewOnStart": "true",
"RunOnceActivity.ShowReadmeOnStart": "true",
"SHARE_PROJECT_CONFIGURATION_FILES": "true",
"com.intellij.testIntegration.createTest.CreateTestDialog.defaultLibrary": "JUnit3",
"com.intellij.testIntegration.createTest.CreateTestDialog.defaultLibrarySuperClass.JUnit3": "junit.framework.TestCase",
"project.structure.last.edited": "Modules",
"project.structure.proportion": "0.15",
"project.structure.side.proportion": "0.2",
"settings.editor.selected.configurable": "MavenSettings"
}
}]]></component>
<component name="RecentsManager">
<key name="MoveFile.RECENT_KEYS">
<recent name="C:\Users\ACER\IdeaProjects\HW2\src\main\java\org\example" />
</key>
<key name="CreateTestDialog.Recents.Supers">
<recent name="junit.framework.TestCase" />
</key>
<key name="CreateTestDialog.RecentsKey">
<recent name="org.example" />
</key>
</component>
<component name="RunManager" selected="Application.Main">
<configuration name="Main" type="Application" factoryName="Application" temporary="true" nameIsGenerated="true">
<option name="MAIN_CLASS_NAME" value="org.example.Main" />
<module name="HW2" />
<extension name="coverage">
<pattern>
<option name="PATTERN" value="org.example.*" />
<option name="ENABLED" value="true" />
</pattern>
</extension>
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
<configuration name="ParserTest.testInvalidIPRangeMultipleDashes" type="JUnit" factoryName="JUnit" temporary="true" nameIsGenerated="true">
<module name="HW2" />
<extension name="coverage">
<pattern>
<option name="PATTERN" value="org.example.*" />
<option name="ENABLED" value="true" />
</pattern>
</extension>
<option name="PACKAGE_NAME" value="org.example" />
<option name="MAIN_CLASS_NAME" value="org.example.ParserTest" />
<option name="METHOD_NAME" value="testInvalidIPRangeMultipleDashes" />
<option name="TEST_OBJECT" value="method" />
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
<configuration name="ParserTest.testMissingIPInput" type="JUnit" factoryName="JUnit" temporary="true" nameIsGenerated="true">
<module name="HW2" />
<extension name="coverage">
<pattern>
<option name="PATTERN" value="org.example.*" />
<option name="ENABLED" value="true" />
</pattern>
</extension>
<option name="PACKAGE_NAME" value="org.example" />
<option name="MAIN_CLASS_NAME" value="org.example.ParserTest" />
<option name="METHOD_NAME" value="testMissingIPInput" />
<option name="TEST_OBJECT" value="method" />
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
<configuration name="ParserTest.testValidCaseWithRangeIP" type="JUnit" factoryName="JUnit" temporary="true" nameIsGenerated="true">
<module name="HW2" />
<extension name="coverage">
<pattern>
<option name="PATTERN" value="org.example.*" />
<option name="ENABLED" value="true" />
</pattern>
</extension>
<option name="PACKAGE_NAME" value="org.example" />
<option name="MAIN_CLASS_NAME" value="org.example.ParserTest" />
<option name="METHOD_NAME" value="testValidCaseWithRangeIP" />
<option name="TEST_OBJECT" value="method" />
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
<configuration name="ParserTest.testValidCaseWithSingleIP" type="JUnit" factoryName="JUnit" temporary="true" nameIsGenerated="true">
<module name="HW2" />
<extension name="coverage">
<pattern>
<option name="PATTERN" value="org.example.*" />
<option name="ENABLED" value="true" />
</pattern>
</extension>
<option name="PACKAGE_NAME" value="org.example" />
<option name="MAIN_CLASS_NAME" value="org.example.ParserTest" />
<option name="METHOD_NAME" value="testValidCaseWithSingleIP" />
<option name="TEST_OBJECT" value="method" />
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
<recent_temporary>
<list>
<item itemvalue="Application.Main" />
<item itemvalue="JUnit.ParserTest.testInvalidIPRangeMultipleDashes" />
<item itemvalue="JUnit.ParserTest.testMissingIPInput" />
<item itemvalue="JUnit.ParserTest.testValidCaseWithRangeIP" />
<item itemvalue="JUnit.ParserTest.testValidCaseWithSingleIP" />
</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="00f5bc34-e1f6-4ecf-baf4-26cf412b6ea4" name="Changes" comment="" />
<created>1699962334601</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1699962334601</updated>
</task>
<servers />
</component>
<component name="Vcs.Log.Tabs.Properties">
<option name="TAB_STATES">
<map>
<entry key="MAIN">
<value>
<State />
</value>
</entry>
</map>
</option>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>HW2</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
\ No newline at end of file
package org.example;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import java.util.concurrent.Future;
public class IPOperations<T> {
String Ip;
List<T> portsStatus;
public IPOperations(String ip,List<T> portsStatus){
this.Ip=ip;
this.portsStatus=portsStatus;
}
public static long ipToLong(InetAddress ip) {
byte[] octets = ip.getAddress();
long result = 0;
for (byte octet : octets) {
result <<= 8;
result |= octet & 0xFF;
}
return result;
}
public static String longToIp(long ip) {
return String.format("%d.%d.%d.%d",
(ip >> 24) & 0xFF,
(ip >> 16) & 0xFF,
(ip >> 8) & 0xFF,
ip & 0xFF);
}
public static long compareIPs(String ip1, String ip2) {
// Compare two IP addresses
try {
return ( ipToLong(InetAddress.getByName(ip1)) - ipToLong(InetAddress.getByName(ip2)) );
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
}
package org.example;
public final class InvalidUserInputException extends Exception {
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 org.example;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
//import PortScanner;
import java.net.UnknownHostException;
import java.net.InetAddress;
public class Main{
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
Target t = null;
try {
String[] ar={"64.233.185.138-64.233.185.140","80-84"};
t = Parser.run(ar);
} 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
System.out.println("Scanning ports for every IP from " + t.targetIP + " to " + t.targetIPEnd + " : " + t.portRange[0] + "-" + t.portRange[1]);
// lists to populate
List<IPOperations<Future<PortStatus>>> futureList1 = new ArrayList<>();
List<IPOperations<PortStatus>> resultList1 = new ArrayList<>();
// ExecutorService
try {
long start = IPOperations.ipToLong(InetAddress.getByName(t.targetIP));
long end = IPOperations.ipToLong(InetAddress.getByName(t.targetIPEnd));
//System.out.println(IPOperations.compareIPs(t.targetIPEnd,t.targetIP));
// loop through provided port range
for (long current = start ; current<=end;current++){
ExecutorService es = Executors.newFixedThreadPool(THREAD_COUNT);
List<Future<PortStatus>> futureListPerIp = new ArrayList<>();
for (int currPort = t.portRange[0]; currPort <= t.portRange[1]; currPort++) {
futureListPerIp.add(PortScanner.isPortOpen(es, IPOperations.longToIp(current), currPort, SCAN_TIMEOUT));
}
IPOperations ip=new IPOperations(IPOperations.longToIp(current),futureListPerIp);
futureList1.add(ip);
es.shutdown();
try {
if (!es.awaitTermination(2, TimeUnit.MINUTES)) {
// timeout elapsed before termination
es.shutdownNow();
}
} catch (InterruptedException e) {
es.shutdownNow();
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
for (IPOperations<Future<PortStatus>> IP : futureList1) {
List<PortStatus> ls=new ArrayList<>();
for (Future<PortStatus> eachFuturePerIp:IP.portsStatus) {
try {
ls.add(eachFuturePerIp.get(2,TimeUnit.MINUTES));
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
} catch (TimeoutException e) {
throw new RuntimeException(e);
}
}
try {
IPOperations ip=new IPOperations(IP.Ip,ls);
resultList1.add(ip);
} catch (Exception e) {
System.err.println("Timeout reached");
System.exit(1);
}
}
// display results
//PortScannerResult r = new PortScannerResult(resultList,t.targetIP ,t.targetIPEnd);
PortScannerResult r = new PortScannerResult(resultList1,t.targetIP ,t.targetIPEnd);
System.out.println(r);
}
}
\ No newline at end of file
package org.example;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.net.InetAddress;
public final class Parser {
/**
* Get target information from user inputs.
*
* @param args arguments from user
*/
public static Target run(String[] args) throws InvalidUserInputException {
Target ret = new Target();
if (args.length != 2 && args.length != 1) {
throw new InvalidUserInputException("default");
}
if (args[0].contains("-")) {
// is a range
// first occurrence of dash
int index = args[0].indexOf("-");
if (isValidIPv4Address(args[0].substring(0, index)) && isValidIPv4Address(args[0].substring(index + 1, args[0].length()))) {
ret.targetIP = args[0].substring(0, index);
ret.targetIPEnd = args[0].substring(index + 1, args[0].length());
} else {
// invalid ip
throw new InvalidUserInputException("ip");
}
}
else {
// a single ip
// set ip
if (isValidIPv4Address(args[0])) {
ret.targetIP = args[0];
ret.targetIPEnd = args[0];
} else {
// invalid ip
throw new InvalidUserInputException("ip");
}
}
// you have to check if the range of ips is correct
if (IPOperations.compareIPs(ret.targetIP, ret.targetIPEnd) > 0) {
throw new InvalidUserInputException("ip");
}
// set port range
String targetPortStart;
String targetPortEnd;
if (args.length == 1) {
// target all possible port if provided ip is valid
targetPortStart = "1";
targetPortEnd = "65535";
} else if (args[1].contains("-")) {
// is a range
// first occurrence of dash
int index = args[1].indexOf("-");
targetPortStart = args[1].substring(0, index);
targetPortEnd = args[1].substring(index + 1, args[1].length());
} else {
// a single port
targetPortStart = args[1];
targetPortEnd = args[1];
}
try {
ret.portRange[0] = Integer.parseInt(targetPortStart);
ret.portRange[1] = Integer.parseInt(targetPortEnd);
// validate range
if (ret.portRange[0] > ret.portRange[1]) {
throw new InvalidUserInputException("port");
}
} catch (Exception e) {
// could not convert port num to int
throw new InvalidUserInputException("port");
}
// check if ports are in valid range
if (!isValidPortNumber(ret.portRange[0]) || !isValidPortNumber(ret.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;
}
}
}
\ No newline at end of file
package org.example;
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(new Callable<PortStatus>() {
@Override
public PortStatus call() {
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 org.example;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.net.InetAddress;
public final class PortScannerResult {
// private String startIp;
// private String endIP;
private List<IPOperations> openList;
private List<IPOperations> closedList;
public PortScannerResult(List<IPOperations<PortStatus>> resultList,String start , String end) {
this.openList = new ArrayList<>();
this.closedList = new ArrayList<>();
// startIp=start;
// endIP=end;
for (IPOperations<PortStatus> eachPortsStatusList : resultList) {
List<PortStatus> openListPerIP = new ArrayList<>();
List<PortStatus> closedListPerIP = new ArrayList<>();
for (PortStatus eachPortStatus:eachPortsStatusList.portsStatus) {
if (eachPortStatus.getIsOpen()) {
openListPerIP.add(eachPortStatus);
} else {
closedListPerIP.add(eachPortStatus);
}
}
IPOperations ipOpenPorts=new IPOperations(eachPortsStatusList.Ip,openListPerIP);
IPOperations ipColsedPorts=new IPOperations(eachPortsStatusList.Ip,closedListPerIP);
openList.add(ipOpenPorts);
closedList.add(ipColsedPorts);
}
}
@Override
public String toString() {
List<StringBuilder> sbs=new ArrayList<>();
StringBuilder sb = new StringBuilder();
int totalCount = openList.get(0).portsStatus.size() + closedList.get(0).portsStatus.size();
for (IPOperations<PortStatus> openPortStatusPerIP : openList) {
sb.append("ip : " + openPortStatusPerIP.Ip + "\n");
sb.append(openPortStatusPerIP.portsStatus.size() + "/" + totalCount + " were open\n");
for (PortStatus openPortStatus:openPortStatusPerIP.portsStatus) {
sb.append(openPortStatus + "\n");
}
// try {
// startIp= IPOperations.longToIp(IPOperations.ipToLong(InetAddress.getByName(startIp)) + 1) ;
// } catch (UnknownHostException e) {
// throw new RuntimeException(e);
// }
}
return sb.toString();
}
}
package org.example;
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;
}
}
\ No newline at end of file
package org.example;
public final class Target {
public String targetIP;
public String targetIPEnd;
public int[] portRange;
public Target() {
portRange = new int[2];
}
}
\ No newline at end of file
package org.example;
import junit.framework.TestCase;
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.util.ArrayList;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class ParserTest {
private ArrayList<String> userArgs;
private static final String SAMPLE_IP_ADDR = "123.123.123.123";
private static final String SAMPLE_IP_ADDR2 = "127.0.0.1";
private String[] getUserArgs() {
return this.userArgs.toArray(new String[this.userArgs.size()]);
}
private Target getExpectedTarget(String IP,String IPEnd, int portStart, int portEnd) {
Target expectedTargetStruct = new Target();
expectedTargetStruct.portRange[0] = portStart;
expectedTargetStruct.portRange[1] = portEnd;
expectedTargetStruct.targetIP = IP;
expectedTargetStruct.targetIPEnd = IPEnd;
return expectedTargetStruct;
}
@Rule
public ExpectedException exceptionRule = ExpectedException.none();
@Before
public void setup() {
userArgs = new ArrayList<>();
}
// test ip
//edit to test single ip
@Test
public void testValidCaseWithSingleIP() {
Target exp = getExpectedTarget(SAMPLE_IP_ADDR, 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);
assertEquals(exp.targetIPEnd, act.targetIPEnd);
} catch (Exception e) {
fail("Unexpected exception :(");
}
}
@Test
public void testInvalidIPRangeMultipleDashes() throws InvalidUserInputException {
// expects exception too
exceptionRule.expect(InvalidUserInputException.class);
exceptionRule.expectMessage("Invalid user input: ip");
// user input multiple dashes for port range
userArgs.add(SAMPLE_IP_ADDR+"--"+SAMPLE_IP_ADDR2);
userArgs.add("14-15");
Parser.run(getUserArgs());
}
// test ports
// edit to test valid case with IP range
@Test
public void testValidCaseWithPortRange() {
Target exp = getExpectedTarget(SAMPLE_IP_ADDR,SAMPLE_IP_ADDR2 ,14, 23);
Target act = null;
userArgs.add(SAMPLE_IP_ADDR+"-"+SAMPLE_IP_ADDR2);
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);
assertEquals(exp.targetIPEnd, act.targetIPEnd);
} catch (Exception e) {
fail("Unexpected exception :(");
}
}
@Test
public void testValidCaseWithSinglePort() {
Target exp = getExpectedTarget(SAMPLE_IP_ADDR, SAMPLE_IP_ADDR2,22, 22);
Target act = null;
userArgs.add(SAMPLE_IP_ADDR+"-"+SAMPLE_IP_ADDR2);
userArgs.add("22");
try {
act = Parser.run(getUserArgs());
assertTrue(Arrays.equals(exp.portRange, act.portRange));
assertEquals(exp.targetIP, act.targetIP);
assertEquals(exp.targetIPEnd, act.targetIPEnd);
} 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+"-"+SAMPLE_IP_ADDR2);
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+"-"+SAMPLE_IP_ADDR2);
userArgs.add("14--15");
Parser.run(getUserArgs());
}
@Test
public void testValidPortRangeAllPorts() {
Target exp = getExpectedTarget(SAMPLE_IP_ADDR, SAMPLE_IP_ADDR2,1, 65535);
Target act = null;
userArgs.add(SAMPLE_IP_ADDR+"-"+SAMPLE_IP_ADDR2);
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 org.example;
import junit.framework.TestCase;
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;
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();
}
}
\ No newline at end of file
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