How to get IP address in Python
The socket module in Python provides access to the BSD socket interface. The socket.gethostbyname(hostname) translate a host name to IPv4 address format. The IPv4 address is returned as a string, such as '192.168.0.1'. If the host name is an IPv4 address itself it is returned unchanged. But, the method gethostbyname() does not support IPv6 name resolution, and getaddrinfo() should be used instead for IPv4/v6 dual stack support.
import socket
print (socket.gethostbyname(socket.gethostname()))
The gethostname() return a string containing the hostname of the machine where the Python interpreter is currently executing.
Translate a host name to IPv4 address format
Version 4 of the Internet Protocol (IPv4) defines an IP address as a 32-bit number . The socket.gethostbyname() method translate a host name to IPv4 address format.
import socket
print (socket.gethostbyname("www.goole.com"))
output
87.106.83.127
Related Topics
- How to find hostname of a computer - Python
- Send mail from Gmail account using Python
- Retrieving Email from a POP3 Server - Python
- Retrieving Web Pages with HTTP using Python
- How to open a web browser using Python
- Creating an FTP client in Python
- Socket Programming in Python
- Multi threaded socket programming in Python