Skip to content

Instantly share code, notes, and snippets.

@akorn
Created December 28, 2025 16:40
Show Gist options
  • Select an option

  • Save akorn/b255a2809a7293da3e900140c3697e53 to your computer and use it in GitHub Desktop.

Select an option

Save akorn/b255a2809a7293da3e900140c3697e53 to your computer and use it in GitHub Desktop.
An LD_PRELOAD library to wrap socket() and apply a SO_MARK value
/** Wrapper utility to mark all sockets of a program
*
* Compile:
* gcc -fPIC -c -o mark.o mark.c
* gcc -shared -o mark.so mark.o -ldl
*
* Usage example:
* MARK=10 LD_PRELOAD=./mark.so wget -qO- ifconfig.me
*
* @author András Korn <[email protected]>
* @author Steffen Vogel <[email protected]>
* @author D.J. Capelis
* @copyright 2025, András Korn
* @copyright 2014-2015, Steffen Vogel
* @copyright 2007, Regents of the University of California
* @license GPLv3
*********************************************************************************/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
#include <sys/types.h>
#include <sys/socket.h>
#define DEF_MARK 0xCD
typedef int (*socket_t)(int domain, int type, int protocol);
static socket_t _socket;
int socket(int domain, int type, int protocol)
{
if (!_socket)
_socket = (socket_t) dlsym(RTLD_NEXT, "socket");
int sd = _socket(domain, type, protocol);
if (sd >= 0) {
if (domain == AF_INET || domain == AF_INET6) {
unsigned mark;
char *endptr, *env = getenv("MARK"), *mark_debug = getenv("MARK_DEBUG");
if (env != NULL) {
mark = strtoul(env, &endptr, 0);
if (env == endptr) /* skip if invalid mark given */
return sd;
}
else
mark = DEF_MARK;
if (mark_debug != NULL) printf("mark: setting SO_MARK for fd=%u to %#x\n", sd, mark);
setsockopt(sd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
}
}
return sd;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment