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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import socket def main(): hostName = socket.gethostname() ipaddr = socket.gethostbyname(hostName) print(" Host Name Is : {} " .format(hostName)) print(" IP Address Is : {} " .format(ipaddr)) if __name__ == "__main__": main() |
First, we need to import the Python socket library as following
1 |
import socket |
Then, we call the gethostname() method from the socket library for the host name and for IP Address we use gethostbyname()
1 2 3 |
hostName = socket.gethostname() ipaddr = socket.gethostbyname(hostName) |
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
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
Neat! Thanks