Created
February 4, 2023 16:45
-
-
Save R3DHULK/bf3d9426e82504714a0f3a77aa014f04 to your computer and use it in GitHub Desktop.
TCP Port Scanner In C Programming
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <unistd.h> | |
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <netinet/in.h> | |
#include <netdb.h> | |
#define MAX_PORT 65535 | |
void error(const char *msg) | |
{ | |
perror(msg); | |
exit(1); | |
} | |
int main(int argc, char *argv[]) | |
{ | |
int sockfd, port; | |
struct sockaddr_in serv_addr; | |
struct hostent *server; | |
if (argc < 2) { | |
fprintf(stderr, "Usage: %s <hostname>\n", argv[0]); | |
exit(1); | |
} | |
server = gethostbyname(argv[1]); | |
if (server == NULL) { | |
fprintf(stderr, "Error: Unable to resolve hostname\n"); | |
exit(1); | |
} | |
memset(&serv_addr, 0, sizeof(serv_addr)); | |
serv_addr.sin_family = AF_INET; | |
serv_addr.sin_port = htons(80); | |
memcpy(&serv_addr.sin_addr, server->h_addr, server->h_length); | |
for (port = 1; port <= MAX_PORT; port++) { | |
sockfd = socket(AF_INET, SOCK_STREAM, 0); | |
if (sockfd < 0) { | |
error("Error: Unable to create socket"); | |
} | |
serv_addr.sin_port = htons(port); | |
if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) == 0) { | |
printf("Port %d is open\n", port); | |
} | |
close(sockfd); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment