It's easy to test for TCP, but how about UDP? Here: Check if OpenVPN UDP Port is open I read that it is impossible to do this. However, here: How to retrieve both TCP and UDP ports with Nmap? it was proved that nmap can do this, so its possible I think.
I wrote a very simple code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
int main(int argc, char **argv)
{
char * ip_addr;
int port;
int sockfd;
struct sockaddr_in server_addr;
if (argc != 3)
{
fprintf(stderr,"Usage: %s IP port \n", argv[0]);
exit(1);
}
ip_addr = argv[1];
port = atoi(argv[2]);
if (port <= 0)
{
fprintf(stderr,"error: invalid port\n");
exit(1);
}
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("socket");
exit(1);
}
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
inet_aton(ip_addr, &server_addr.sin_addr);
char msg[] = "Just a text\n";
char buffer[255];
int recv_size, send_size;
if ((send_size = sendto(sockfd, msg, strlen(msg), 0, (struct sockaddr*) &server_addr, sizeof(server_addr))) < 0)
{
close(sockfd);
if (errno != 0)
{
perror("send");
exit(1);
}
}else if(send_size == 0)
{
printf("sent\n");
}
else if (send_size > 0)
{
printf("sent\n");
}
if ((recv_size = recvfrom(sockfd, buffer, 255, 0, NULL, NULL)) == 0)
{
close(sockfd);
if (errno != 0)
{
perror("recv");
exit(1);
}
}
buffer[recv_size] = '\0';
close(sockfd);
return 0;
}
But it prints nothing, just ends. So its hard to say what happend, if the port is opened or not. Is there a simple way, using sockets, to test whether the remote UDP port is opened?