Skip to content

Instantly share code, notes, and snippets.

@R3DHULK
Created February 4, 2023 17:09
Show Gist options
  • Save R3DHULK/3cd7b1992eda3c8b3ac420a6802c0cfc to your computer and use it in GitHub Desktop.
Save R3DHULK/3cd7b1992eda3c8b3ac420a6802c0cfc to your computer and use it in GitHub Desktop.
Port Scanning In CPP
#include <iostream>
#include <cstring>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <vector>
using namespace std;
vector<int> ports = {21, 22, 23, 25, 80, 110, 443};
int main(int argc, char* argv[]) {
if (argc != 2) {
cout << "Usage: %s <IP address>" << endl;
return -1;
}
char* target = argv[1];
for (int port : ports) {
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
cout << "Could not create socket." << endl;
return -1;
}
sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
inet_pton(AF_INET, target, &addr.sin_addr);
int res = connect(sock, (sockaddr*) &addr, sizeof(addr));
if (res == -1) {
cout << "Port " << port << " is closed." << endl;
} else {
cout << "Port " << port << " is open." << endl;
}
close(sock);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment