package com.techcavern.wavetact.ircCommands.dnsinfo;

import com.techcavern.wavetact.annot.IRCCMD;
import com.techcavern.wavetact.objects.IRCCommand;
import com.techcavern.wavetact.utils.ErrorUtils;
import com.techcavern.wavetact.utils.GeneralUtils;
import com.techcavern.wavetact.utils.IRCUtils;
import org.pircbotx.Channel;
import org.pircbotx.PircBotX;
import org.pircbotx.User;

import java.net.ConnectException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

@IRCCMD
public class CheckPort extends IRCCommand {

    public CheckPort() {
        super(GeneralUtils.toArray("checkport cport"), 0, "checkport (+)[ip][domain] (port)", " Checks if port is open on a certain ip and port", false);
    }

    @Override
    public void onCommand(User user, PircBotX network, String prefix, Channel channel, boolean isPrivate, int userPermLevel, String... args) throws Exception {
        boolean IPv6Priority = false;
        if(args[0].startsWith("+")){
            IPv6Priority = true;
            args[0] = args[0].replaceFirst("\\+","");
        }
        int port;
        if (args.length < 2) {
            port = 80;
        } else {
            port = Integer.parseInt(args[1]);
        }
        String IP = GeneralUtils.getIP(args[0], network, IPv6Priority);
        try {
            if (InetAddress.getByName(IP).isAnyLocalAddress()) {
                IRCUtils.sendMessage(user, network, channel, "I cannot find myself! :<", prefix);
                return;
            }
        } catch (UnknownHostException e) {
            //do nothing
        }
        if (IP == null) {
            ErrorUtils.sendError(user, "Host Unreachable");
        } else {
            try {
                Socket socket = new Socket(IP, port);
                socket.close();
                IRCUtils.sendMessage(user, network, channel, "Port " + port + " is open on " + IP, prefix);
            } catch (ConnectException e) {
                if (e.getMessage().equals("Connection refused"))
                    IRCUtils.sendMessage(user, network, channel, "Port " + port + " is closed on " + IP, prefix);
                else
                    ErrorUtils.sendError(user, "Host Unreachable");
            }
        }

    }
}
@@ -396,115 +396,9 @@
 net.
-ConnectException;%0Aimport java.net.InetAddress;%0Aimport java.net.Socket;%0Aimport java.net.UnknownHostException
+*
 ;%0A%0A@
@@ -1655,16 +1655,72 @@
  Socket(
+);%0A                socket.connect(new InetSocketAddress(
 IP, port
@@ -1720,16 +1720,23 @@
 P, port)
+, 1000)
 ;%0A      
@@ -1890,23 +1890,16 @@
  catch (
-Connect
 Exceptio
@@ -1909,77 +1909,8 @@
 ) %7B%0A
-                if (e.getMessage().equals(%22Connection refused%22))%0A    
     
@@ -2019,97 +2019,8 @@
 x);%0A
-                else%0A                    ErrorUtils.sendError(user, %22Host Unreachable%22);%0A
     

Set Socket Timeout