Monday, April 21, 2025

Get Real IP Address from Localhost Name - Python

import socket

name_of_this_pc = socket.gethostname()

print("Name: " + name_of_this_pc)

print("IP: " + socket.gethostbyname(name_of_this_pc))

This Python code performs the following tasks:

  1. Imports the 'socket' module using the 'import' keyword. This module provides a way to communicate over a network.

  2. Calls the 'socket.gethostname()' method, which returns the hostname of the current machine on which the Python script is running. This hostname is assigned to a variable called 'name_of_this_pc'.

  3. Prints a string to the console, which contains the hostname of the machine. The 'print()' function is used to output the string, which includes the 'Name:' label followed by the value of the 'name_of_this_pc' variable.

  4. Calls the 'socket.gethostbyname()' method, passing the 'name_of_this_pc' variable as an argument. This method returns the IP address of the machine with the given hostname.

  5. Prints a string to the console that includes the IP address of the machine. The 'print()' function is used to output the string, which includes the 'IP:' label followed by the value of the 'socket.gethostbyname(name_of_this_pc)' method.

Let's break down each line of code in more detail:

import socket

This line imports the 'socket' module into the script, which provides access to the socket interface for network communication.

name_of_this_pc = socket.gethostname()

This line calls the 'socket.gethostname()' method, which returns the hostname of the current machine. The returned value is then assigned to the 'name_of_this_pc' variable for later use.

print("Name: " + name_of_this_pc)

This line prints a string to the console, which includes the hostname of the machine. The 'print()' function is used to output the string, which includes the 'Name:' label followed by the value of the 'name_of_this_pc' variable.

print("IP: " + socket.gethostbyname(name_of_this_pc))

This line calls the 'socket.gethostbyname()' method, passing the 'name_of_this_pc' variable as an argument. This method returns the IP address of the machine with the given hostname. The 'print()' function is then used to output a string to the console that includes the IP address of the machine. The string includes the 'IP:' label followed by the value of the 'socket.gethostbyname(name_of_this_pc)' method.

This script retrieves and displays the hostname and IP address of the machine on which it is running.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...