Skip to content

Instantly share code, notes, and snippets.

@yousong
Last active May 8, 2018 12:30
Show Gist options
  • Save yousong/303ed53967f7fbe6bbf804fea8a80309 to your computer and use it in GitHub Desktop.
Save yousong/303ed53967f7fbe6bbf804fea8a80309 to your computer and use it in GitHub Desktop.
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
struct buf_t {
char *start;
int len;
};
int fd;
int val = 1;
struct sockaddr_in addr;
struct buf_t buf;
void loop() {
struct msghdr msgh;
struct iovec iov;
struct cmsghdr *cmsg;
int rv;
struct sockaddr_in from;
struct in_pktinfo to;
char cbuf[512];
buf.len = 4096;
buf.start = malloc(buf.len);
while (true) {
memset(&msgh, 0, sizeof(struct msghdr));
iov.iov_base = buf.start;
iov.iov_len = buf.len;
msgh.msg_control = cbuf;
msgh.msg_controllen = sizeof(cbuf);
msgh.msg_name = &from;
msgh.msg_namelen = sizeof(from);
msgh.msg_iov = &iov;
msgh.msg_iovlen = 1;
msgh.msg_flags = 0;
rv = recvmsg(fd, &msgh, 0);
for (cmsg = CMSG_FIRSTHDR(&msgh);
cmsg != NULL;
cmsg = CMSG_NXTHDR(&msgh, cmsg)) {
if (cmsg->cmsg_level == IPPROTO_IP && cmsg->cmsg_type == IP_PKTINFO) {
to = *(struct in_pktinfo *)CMSG_DATA(cmsg);
}
}
iov.iov_len = rv;
rv = sendmsg(fd, &msgh, 0);
if (rv < 0) {
fprintf(stderr, "sendmsg: %s\n", strerror(errno));
}
}
}
int main() {
fd = socket(AF_INET, SOCK_DGRAM, 0);
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
setsockopt(fd, SOL_SOCKET, SO_NO_CHECK, &val, sizeof(val));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = 0;
addr.sin_port = htons(1701);
bind(fd, (struct sockaddr *)&addr, sizeof(addr));
setsockopt(fd, IPPROTO_IP, IP_PKTINFO, &val, sizeof(val));
#define IP_IPSEC_REFINFO 30
setsockopt(fd, IPPROTO_IP, IP_IPSEC_REFINFO, &val, sizeof(val));
loop();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment