kill port already in use

require 'socket'

def find_available_port(start_port)
  port = start_port.to_i
  loop do
    begin
      TCPServer.new('127.0.0.1', port).close
      return port
    rescue Errno::EADDRINUSE
      port += 1
    end
  end
end

def kill_process_using_port(port)
  pid = `lsof -t -i:#{port}`
  Process.kill('TERM', pid.to_i) unless pid.empty?
end

# Example usage:
# Choose a starting port
start_port = 3000

# Find an available port starting from the chosen port
available_port = find_available_port(start_port)

# Kill any process currently using the available port
kill_process_using_port(available_port)

puts "Available port: #{available_port}"

Explanation:

  1. Require the socket library to work with TCP sockets in Ruby.

  2. Define a method find_available_port that takes a starting port as an argument and returns the first available port by attempting to create a TCP server socket on each port, incrementing the port number until an available port is found.

  3. Define a method kill_process_using_port that takes a port number as an argument, uses the lsof command to find the process ID (pid) using that port, and kills the process if a pid is found.

  4. Set a starting port (e.g., 3000) for the search.

  5. Find an available port starting from the chosen port using the find_available_port method.

  6. Kill any process currently using the available port using the kill_process_using_port method.

  7. Print the available port to the console.

Note: Ensure that the script has the necessary permissions to kill processes, and this script is primarily for educational purposes. Killing processes can have unintended consequences, and it's essential to use caution and consider potential impacts before applying this in a production environment.