commit dff2c19a0738b02f3024b07446d952045f75fbad
parent 120ec87fd77624a5c99f6318ac2599dbf0b91261
Author: Robin Bron <robin@finwo.nl>
Date: Wed, 27 Apr 2022 21:33:47 +0200
Separated raw socket creation from main
Diffstat:
3 files changed, 75 insertions(+), 29 deletions(-)
diff --git a/src/main.c b/src/main.c
@@ -10,6 +10,8 @@
#include <linux/if_packet.h>
+#include "socket.h"
+
#ifdef __cplusplus
extern "C" {
#endif
@@ -18,34 +20,7 @@ extern "C" {
#define ERR_NAME "pmlag"
int main(int argc, char **argv) {
-
- // Open socket
- int sockfd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
- if (sockfd < 0) {
- perror(ERR_NAME ": socket");
- exit(EXIT_FAILURE);
- }
-
- struct sockaddr_ll sll;
- struct ifreq ifr;
- bzero(&sll, sizeof(sll));
- bzero(&ifr, sizeof(ifr));
-
- // Get interface index
- strncpy((char *)ifr.ifr_name, INTERFACE, IFNAMSIZ);
- if ((ioctl(sockfd, SIOCGIFINDEX, &ifr)) == -1) {
- perror(ERR_NAME ": Error getting interface index");
- exit(EXIT_FAILURE);
- }
-
- // Bind socket to interface
- sll.sll_family = AF_PACKET;
- sll.sll_ifindex = ifr.ifr_ifindex;
- sll.sll_protocol = htons(ETH_P_ALL);
- if((bind(sockfd, (struct sockaddr *)&sll, sizeof(sll))) == -1) {
- perror(ERR_NAME ": Error binding raw socket to interface");
- exit(EXIT_FAILURE);
- }
+ int sockfd = sockraw_open(INTERFACE);
// Prepare ingress buffer
int buflen;
@@ -98,7 +73,7 @@ int main(int argc, char **argv) {
printf("\n");
}
- return 42;
+ return 0;
}
#ifdef __cplusplus
diff --git a/src/socket.c b/src/socket.c
@@ -0,0 +1,57 @@
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <arpa/inet.h>
+#include <net/ethernet.h>
+#include <net/if.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/socket.h>
+#include <unistd.h>
+
+#include <linux/if_packet.h>
+
+int sockraw_open(char * ifname) {
+
+ // Open socket
+ int sockfd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
+ if (sockfd < 0) {
+ perror("Error opening socket");
+ close(sockfd);
+ return -1;
+ }
+
+ struct sockaddr_ll sll;
+ struct ifreq ifr;
+ bzero(&sll, sizeof(sll));
+ bzero(&ifr, sizeof(ifr));
+
+ // Get interface index
+ strncpy((char *)ifr.ifr_name, ifname, IFNAMSIZ);
+ if ((ioctl(sockfd, SIOCGIFINDEX, &ifr)) == -1) {
+ perror("Error getting interface index");
+ close(sockfd);
+ return -1;
+ }
+
+ // Bind socket to interface
+ sll.sll_family = AF_PACKET;
+ sll.sll_ifindex = ifr.ifr_ifindex;
+ sll.sll_protocol = htons(ETH_P_ALL);
+ if((bind(sockfd, (struct sockaddr *)&sll, sizeof(sll))) == -1) {
+ perror("Error binding raw socket to interface");
+ close(sockfd);
+ return -1;
+ }
+
+ // Return the prepared socket
+ return sockfd;
+}
+
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
diff --git a/src/socket.h b/src/socket.h
@@ -0,0 +1,14 @@
+#ifndef __PMLAG_SOCKET_H__
+#define __PMLAG_SOCKET_H__
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+int sockraw_open(char * ifname);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+#endif // __PMLAG_SOCKET_H__