pythoncrandomreverse-engineeringrandom-seed

How to mimic rand() function of C in python?


I want to convert the following C code to python :

timeVar = time((time_t *)0x0)
seed = (uint)timeVar;
srand(seed);
random_value1 = rand();
random_value2 = rand();
random_value3 = rand();

Basically, i have a seed used in the C code i provided earlier, and i want to make the same code in python to predict the next values based on the seed i have.

Edit : I found that it can be solved with ctypes module.


Solution

  • Using the ctypes module would let you call rand from libc. Whether this is the same rand as is being used by your program is a different matter (e.g. it might be statically linked to another implemention of rand) but it might work!

    from ctypes import CDLL
    from ctypes.util import find_library
    
    libc = CDLL(find_library("c"))
    
    libc.srand(0x5a35b162)
    print(libc.rand(), libc.rand(), libc.rand())
    

    Note that Python doesn't know the prototypes of these methods, but given the're small integer values it likely doesn't matter much. But have a read of the section on foreign functions if you're interested.