How to get IP address in Python

The Python socket module grants access to the BSD socket interface. The socket.gethostbyname(hostname) function translates a hostname into IPv4 address format, returning the address as a string like '192.168.0.1'. If the hostname is already in IPv4 address format, it remains unchanged. However, note that the gethostbyname() method doesn't support IPv6 name resolution, and for IPv4/v6 dual stack support, the getaddrinfo() method should be employed instead.

import socket print (socket.gethostbyname(socket.gethostname()))

The gethostname() function returns a string that contains the hostname of the machine on which the Python interpreter is presently running.

Translate a host name to IPv4 address format

IPv4, which is Internet Protocol version 4, defines an IP address as a 32-bit numerical value. The socket.gethostbyname() method serves to convert a hostname into the IPv4 address format.

import socket print (socket.gethostbyname("www.goole.com"))
output
87.106.83.127

Conclusion

To retrieve the IP address of a client using Python, you can use the socket.gethostbyname() function to translate a hostname into its corresponding IPv4 address. This enables you to identify the client's IP address within a network environment.