#define _GNU_SOURCE #include #include #include #include #include #include #include #include #include #include #include static int (*real_socket)(int domain, int type, int protocol) = NULL; __attribute__((constructor)) void init(void) { real_socket = dlsym(RTLD_NEXT, "socket"); if (!real_socket) { fprintf(stderr, "Error loading original socket function\n"); exit(1); } } int socket(int domain, int type, int protocol) { int sockfd = real_socket(domain, type, protocol); if (sockfd == -1) { return -1; } char *interface = getenv("SOCKET_INTERFACE"); if (interface) { FILE *log = fopen("/tmp/socket_bind.log", "a"); if (log) { fprintf(log, "Binding socket %d to interface %s\n", sockfd, interface); fflush(log); // Ensure the log is written immediately fclose(log); } if (setsockopt(sockfd, SOL_SOCKET, SO_BINDTODEVICE, interface, strlen(interface)) < 0) { FILE *log = fopen("/tmp/socket_bind.log", "a"); if (log) { fprintf(log, "Failed to bind socket to interface %s: %s\n", interface, strerror(errno)); fflush(log); // Ensure the log is written immediately fclose(log); } close(sockfd); return -1; } } return sockfd; }