Display the Host Name and IP Address on a Tkinter Window

To obtain a user's IP address, we can use Python's native networking interface, socket. First of all, we need to query the device's host name and then get its associated IP address.

In this example, we will use the socket library to get the host name and IP address and print the details on two labels.

Steps −

  • Import the tkinter library and create an instance of tkinter frame.

  • Set the size of the frame using geometry method.

  • Next, use the gethostname() method of socket library to get the host name and store it in a variable "hostname".

  • Then use the gethostbyname() method and pass the hostname in it to get the IP address.

  • Create two labels to display the hostname and IP address on the window.

  • Finally, run the mainloop of the application window.


# Import the tkinter library
from tkinter import *
import socket

# Create an instance of tkinter frame
root = Tk()

# Size of the window

# hostname of the socket
hostname = socket.gethostname()

# IP address of the hostname
ip_address = socket.gethostbyname(hostname)

label1 = Label(root, text="The Host Name is: " + hostname, font = "Calibri, 20")

label2 = Label(root, text="The IP Address is: " + ip_address, font = "Calibri, 20")



It will produce the following output −