问题
I have test code that I want to have a couple of hostnames resolve to the loopback while testing. When deployed, this code will use the normal system name resolution as appropriate. Test and deployment host are recent linux distros (SLES11SP1, e.g.).
I'd like to override hostname resolution for a single process, without being superuser. Is there a way to manipulate the nsswitch
/hosts
behavior in such a narrow fashion?
Yes, of course I could override the hostnames themselves, but I prefer not to (unless this feature really isn't available).
EDIT:
glibc
's HOSTALIASES
feature sounds like exactly what I want -- but its availability/effectiveness seems inconsistent among the hosts I surveyed. At some point, it was added to be among a list of insecure environment variables. But does that mean it's ignored globally or only in suid binaries? Will it still work for programs which do getnameinfo
()?
More edit:
IMO, HOSTALIAS
wins hands down. Disabling nscd
is a workaround for platforms which don't respect it -- like mine (SuSE). And maybe they will release a fix.
回答1:
LD_LIBRARY_PATH for the win!
http://tldp.org/HOWTO/Program-Library-HOWTO/shared-libraries.html
Also: What is the LD_PRELOAD trick?
Also: http://www.linuxjournal.com/article/7795
回答2:
Assuming you want to intercept e.g. gethostbyname()
, and have it return 127.0.0.1
for certain hostnames ...
If your code is C++, the simplest answer might be to use gMock.
If you can't, you may want to interpose gethostbyname
. A sample interposer is documented here.
回答3:
Brian, another option would be to use chroot. You could create a directory with a bunch of mount --rbind for each of the directories usr, lib, home, etc. - enough to simulate a working root directory. Then use mount -t aufs to "layer" mount the existing etc together with a writable empty layer. In essence, after all that, whatever you change in etc ends up changing only inside that chroot environment. You could override and simulate all kinds of environments that way. If this is of any interest and need me to elaborate further, let me know.
来源:https://stackoverflow.com/questions/7934027/process-local-override-of-name-resolution