When creating robust and maintanance-free applications sometimes you are required to determine the outgoing IP address of your local comuter.
This article will show you how to fetch this address by utilizing features of your operating system without opening connections to remote servers!
Fetching the outgoing IP address of a computer might be a difficult task. Computers can contain a large set of network devices, each connected to different and independent sub-networks. Additionally there might be available a number of devices, to be utilized in the manner of network devices to exchange data with external systems.
However, if properly configured, your operating system knows what device has to be utilized. Querying results depend on target addresses and routing information. In our solution we are utilizing the features of the local operating system to determine the correct network device. I the same step we will get the associated network address.
To reach this goal we will utilize the UDP protocol. Unlike TCP/IP, UDP is a stateless networking protocol to transfer single data packages. You do not have to open a point-to-point connection to a service running at the target host. We have to provide the target address to enable the operating system to find the correct device. Due to the nature of UDP you are not required to choose a valid target address. You just have to make sure your are choosing an arbitrary address from the correct subnet.
The following function is temporarily opening a UDP server socket. It is returning the IP address associated with this socket.
import socket def get_local_ip_address(target): ipaddr = '' try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect((target, 8000)) ipaddr = s.getsockname()[0] s.close() except: pass return ipaddr
Here are some examples how to utilize the previous script.
# some examples how to utilize the previous script # find out the device responsible for connecting to ... >>> print(get_local_ip_address('linux-support.com')) 10.132.1.98 >>> print(get_local_ip_address('1.1.1.1')) 10.132.1.98 >>> print(get_local_ip_address('192.168.1.150')) 192.168.1.102 >>> print(get_local_ip_address('127.0.0.77')) 127.0.0.1
Related articles: