11

From within a Python script I am trying to get the host name in a Linux box. It is a Debian GNU/Linux Amazon EC2 instance. I have set the correct name in /etc/hostname. The recommended solution socket.gethostname() is not working: it shows the ip- plus the IP tuple.

I have searched on StackOverflow and nothing is coming out, e.g. here. socket.getfqdn() is even worse: it yields ip-[IP tuple].eu-west-1.compute.internal.

Am I doing something wrong, or is there no clean solution to get the hostname in /etc/hostname? Of course the back-up solution is to read the file etc/hostname itself, but something so inherently platform-dependent is somehow too aberrant. Thanks!

2
  • 4
    do you see desired hostname when you do uname -n ? in case no try executing /etc/init.d/hostname.sh Commented Nov 24, 2011 at 22:58
  • Amazing! That was it. Now socket.gethostname() returns the correct hostname. So the problem was just that the machine had not been rebooted and it had not taken the new hostname. If you want to answer the question with this info I will upvote it. Commented Nov 25, 2011 at 8:36

4 Answers 4

13

Try os.uname(). According to the doc, it is the second position in the tuple returned.

But, as the doc itself states, the "better way to get the hostname is socket.gethostname() or even socket.gethostbyaddr(socket.gethostname())."

Sign up to request clarification or add additional context in comments.

Comments

9

First of all, all credit should go to m1k3y02, who gave me the hint in a comment. Now, for the sake of posterity I will give the correct answer: my Amazon EC2 has not been rebooted in a long time. I set the hostname in /etc/hostname but it did not reach the system, as evidenced by uname -n. So simply running /etc/init.d/hostname.sh did the trick. After that, socket.gethostname() worked as intended.

The lesson here: first see if the system gets it, and only after that blame the language.

Comments

7

The generic source for the hostname is hostname(1). This program calls the equivalent of uname -n.

In Python, you can either use platform.node() or os.uname()[1].

Comments

5

Have you tried socket.gethostbyaddr(socket.gethostname())?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.