Created
April 16, 2020 18:27
-
-
Save bartlomiejn/488a6a3f1b5e7cf7a5dfba042abddcc9 to your computer and use it in GitHub Desktop.
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 <string.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <netinet/in.h> | |
#include <netdb.h> | |
int port_scan(char *addr) | |
{ | |
int sockfd; | |
int err; | |
uint16_t portno; | |
struct addrinfo hints; | |
struct addrinfo *addr_info; | |
struct addrinfo *temp; | |
/* Allow IPv4 or IPv6, stream socket with any protocol */ | |
memset(&hints, 0, sizeof(struct addrinfo)); | |
hints.ai_family = AF_UNSPEC; | |
hints.ai_socktype = SOCK_STREAM; | |
hints.ai_flags = 0; | |
hints.ai_protocol = 0; | |
printf("Ports open for %s:\n", addr); | |
/* Iterate through each port */ | |
for (portno = 0; portno < UINT16_MAX; portno++) | |
{ | |
size_t length = snprintf(NULL, 0, "%d", portno); | |
char* portno_str = malloc(length + 1); | |
snprintf(portno_str, length + 1, "%d", portno); | |
err = getaddrinfo(addr, portno_str, &hints, &addr_info); | |
if (err) | |
{ | |
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(err)); | |
return err; | |
} | |
for (temp = addr_info; temp != NULL; temp = temp->ai_next) | |
{ | |
sockfd = socket(temp->ai_family, | |
temp->ai_socktype, | |
temp->ai_protocol); | |
if (sockfd < 0) | |
{ | |
fprintf(stderr, "Error opening a socket.\n"); | |
continue; | |
} | |
err = connect(sockfd, temp->ai_addr, temp->ai_addrlen); | |
if (err) | |
{ | |
close(sockfd); | |
continue; | |
} | |
printf("%s\n", portno_str); | |
close(sockfd); | |
} | |
freeaddrinfo(addr_info); | |
free(portno_str); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment