Python Socket Programming How to Get IP Address

Python Socket Programming How to Get IP Address – Sometimes, you need to quickly discover some information about your machine, for example,
the host name, IP address, number of network interfaces, and so on. This is very easy to achieve using Python scripts.

 

Also you can check Python Socket Programming Articles

 

1: Python Socket Programming How To Create Socket

 

So now this is the complete code Python Socket Programming How to Get IP Address

 

 

 

First, we need to import the Python socket library as following

 

 

 

Then, we call the gethostname() method from the socket library for the host name and for IP Address we use gethostbyname()

 

 

 

The entire activity can be wrapped in a  function, main(),
which uses the built-in socket class methods.
We call our function from the usual Python __main__ block. During runtime, Python assigns
values to some internal variables such as __name__. In this case, __name__ refers to the
name of the calling process. When running this script from the command line, the name will be __main__, but it will be different if the module is

imported from another script. This means that when the module is called from the command
line, it will automatically run our main() function; however, when imported
separately, the user will need to explicitly call the function.

 

 

Run the complete code and this will be the result

 

Python Socket Programming How to Get IP Address
Python Socket Programming How to Get IP Address

 

 

How it Works

The import socket statement imports one of Python’s core networking libraries. Then, we use
the two utility functions, gethostname() and gethostbyname(host_name). You can type
help(socket.gethostname) to see the online help information from within the command
line. Alternately, you can type the following address in your web browser at http://docs.
python.org/3/library/socket.html.

 

 

 

Also you can watch the complete video for this article 

 

Subscribe and Get Free Video Courses & Articles in your Email

 

1 thought on “Python Socket Programming How to Get IP Address”

Comments are closed.

Share via
Copy link
Powered by Social Snap
×