Skip to content

Instantly share code, notes, and snippets.

@bartlomiejn
Created April 16, 2020 18:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bartlomiejn/488a6a3f1b5e7cf7a5dfba042abddcc9 to your computer and use it in GitHub Desktop.
Save bartlomiejn/488a6a3f1b5e7cf7a5dfba042abddcc9 to your computer and use it in GitHub Desktop.
#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