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!
In order to get the hostname of a computer, you can use socket and its gethostname() functionality. The gethostname() return a string containing the hostname of the machine where the Python interpreter is currently executing.
Use the socket. getsockname() Funtion to Get the Local IP Address in Python. If the computer device has a route connected to the Internet, then we can use the getsockname() function. It returns the IP address and port in the form of a tuple.
On the Internet, a hostname is a domain name assigned to a host computer. For example, if Computer Hope had two computers on its network named "bart" and "homer," the domain name "bart.computerhope.com" is connecting to the "bart" computer.
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.
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())
."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With