Skip to content

Instantly share code, notes, and snippets.

@RecursiveG
Created December 24, 2017 07:08
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 RecursiveG/7f13b75b8dc4478078f2653427656f3b to your computer and use it in GitHub Desktop.
Save RecursiveG/7f13b75b8dc4478078f2653427656f3b to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <linux/udp.h>
int main(int argc, char *argv[])
{
if (argc != 2) {
printf("Usage: %s <port_number>\n", argv[0]);
return -1;
}
char *endptr;
long port_number = strtol(argv[1], &endptr, 0);
if (0 != *endptr || port_number < 0 || port_number > 65535) {
printf("Invalid port number\n");
return -1;
}
int sockfd = -1;
if (0 > (sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))) {
perror("socket() failed");
return -1;
}
struct sockaddr_in host_addr;
memset(&host_addr, 0, sizeof(host_addr));
host_addr.sin_family = AF_INET;
host_addr.sin_port = htons(port_number & 0xFFFFu);
host_addr.sin_addr.s_addr = htonl(INADDR_ANY);
int type = UDP_ENCAP_ESPINUDP;
if (0 > setsockopt(sockfd, IPPROTO_UDP, UDP_ENCAP, &type, sizeof(type))) {
perror("setsockopt() failed to set UDP_ENCAP");
return -1;
}
if (0 > bind(sockfd, (struct sockaddr*) &host_addr, sizeof(host_addr))) {
perror("bind() failed");
return -1;
}
printf("Port opened\n");
while(1) {
sleep(1);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment