IP Address Validation C# Code Snippet

using IPAVReference;

namespace ip_address_validation_dot_net.SOAP
{
    /// <summary>
    /// Provides functionality to call the ServiceObjects IP Address Validation SOAP service's GetGeoLocationByIP_V4 operation,
    /// retrieving geographic location, proxy, host name, and US region information for a given IP address with fallback to a backup endpoint
    /// for reliability in live mode.
    /// </summary>
    public class GetGeoLocationByIPV4Validation
    {
        private const string LiveBaseUrl = "https://sws.serviceobjects.com/GPP/soap.svc/SOAP";
        private const string BackupBaseUrl = "https://swsbackup.serviceobjects.com/GPP/soap.svc/SOAP";
        private const string TrialBaseUrl = "https://trial.serviceobjects.com/GPP/soap.svc/SOAP";

        private readonly string _primaryUrl;
        private readonly string _backupUrl;
        private readonly int _timeoutMs;
        private readonly bool _isLive;

        /// <summary>
        /// Initializes URLs/timeout/IsLive.
        /// </summary>
        public GetGeoLocationByIPV4Validation(bool isLive)
        {
            _timeoutMs = 10000;
            _isLive = isLive;

            _primaryUrl = isLive ? LiveBaseUrl : TrialBaseUrl;
            _backupUrl = isLive ? BackupBaseUrl : TrialBaseUrl;

            if (string.IsNullOrWhiteSpace(_primaryUrl))
                throw new InvalidOperationException("Primary URL not set.");
            if (string.IsNullOrWhiteSpace(_backupUrl))
                throw new InvalidOperationException("Backup URL not set.");
        }

        /// <summary>
        /// Retrieves geographic location, proxy, host name, and US region information for a given IP address.
        /// Consults IP address validation databases to provide details such as city, region, country, latitude, longitude,
        /// proxy status, ISP, and more. The operation returns a single response per IP address.
        /// </summary>
        /// <param name="IPAddress">The IP address to look up, e.g., "209.85.173.104".</param>
        /// <param name="LicenseKey">Your license key to use the service.</param>
        /// <returns>A <see cref="Task{IP4}"/> containing an <see cref="IP4"/> object with geographic location details or an error.</returns>
        /// <exception cref="Exception">Thrown if both primary and backup endpoints fail.</exception>
        public async Task<IP4> GetGeoLocationByIPV4(string IPAddress, string LicenseKey)
        {
            IPSOAPClient clientPrimary = null;
            IPSOAPClient clientBackup = null;

            try
            {
                // Attempt primary endpoint
                clientPrimary = new IPSOAPClient();
                clientPrimary.Endpoint.Address = new System.ServiceModel.EndpointAddress(_primaryUrl);
                clientPrimary.InnerChannel.OperationTimeout = TimeSpan.FromMilliseconds(_timeoutMs);

                IP4 response = await clientPrimary.GetLocationByIP_V4Async(IPAddress, LicenseKey).ConfigureAwait(false);

                if (_isLive && !IsValid(response))
                {
                    throw new InvalidOperationException("Primary endpoint returned null or a fatal Number=4 error for GetGeoLocationByIP_V4");
                }
                return response;
            }
            catch (Exception primaryEx)
            {
                try
                {
                    clientBackup = new IPSOAPClient();
                    clientBackup.Endpoint.Address = new System.ServiceModel.EndpointAddress(_backupUrl);
                    clientBackup.InnerChannel.OperationTimeout = TimeSpan.FromMilliseconds(_timeoutMs);

                    return await clientBackup.GetLocationByIP_V4Async(IPAddress, LicenseKey).ConfigureAwait(false);
                }
                catch (Exception backupEx)
                {
                    throw new Exception(
                        $"Both primary and backup endpoints failed.\n" +
                        $"Primary error: {primaryEx.Message}\n" +
                        $"Backup error: {backupEx.Message}");
                }
                finally
                {
                    clientBackup?.Close();
                }
            }
            finally
            {
                clientPrimary?.Close();
            }
        }

        private static bool IsValid(IP4 response) => response?.Error == null || response.Error.Number != "4";
    }
}

IP Address Validation Python Code Snippet

mIPAddress = IPAddress.get()
if mIPAddress is None or  mIPAddress == "":
     mIPAddress = " "
mLicenseKey = LicenseKey.get()
if mLicenseKey is None or mLicenseKey == "":
    mLicenseKey = " "
 
#Set the primary and backup URLs as needed
primaryURL = 'https://trial.serviceobjects.com/gpp/soap.svc?wsdl'
backupURL = 'https://trial.serviceobjects.com/gpp/soap.svc?wsdl'
#This block of code calls the web service and prints the resulting values to the screen
try:
    client = Client(primaryURL)
    result = client.service.GetLocationByIP_V4(IPAddress= mIPAddress, LicenseKey=mLicenseKey)
    #Handel response and check for errors
#Tries the backup URL if the primary URL failed
except:
from suds.client import Client
from suds import WebFault
from suds.sudsobject import Object

class GetGeoLocationByIPV4Soap:
    def __init__(self, license_key: str, is_live: bool, timeout_ms: int = 10000):
        """
        license_key: Service Objects IPAV license key.
        is_live: Whether to use live or trial endpoints
        timeout_ms: SOAP call timeout in milliseconds
        """
        self._timeout_s = timeout_ms / 1000.0  # Convert to seconds
        self._is_live = is_live
        self.license_key = license_key

        # WSDL URLs for primary and backup endpoints
        self._primary_wsdl = (
            "https://sws.serviceobjects.com/GPP/soap.svc?wsdl"
            if is_live else
            "https://trial.serviceobjects.com/GPP/soap.svc?wsdl"
        )
        self._backup_wsdl = (
            "https://swsbackup.serviceobjects.com/GPP/soap.svc?wsdl"
            if is_live else
            "https://trial.serviceobjects.com/GPP/soap.svc?wsdl"
        )

    def get_geo_location_by_ip_v4(self, ip_address: str) -> Object:
        """
        Calls the IP Address Validation GetGeoLocationByIP_V4 SOAP API to retrieve geographic location, proxy, host name, and US region information.

        Parameters:
            ip_address (str): The IP address to look up, e.g., "209.85.173.104".
            license_key: Service Objects IPAV license key.
            is_live: Whether to use live or trial endpoints
            timeout_ms: SOAP call timeout in milliseconds

        Returns:
            Object: Parsed SOAP response with geolocation information or error details.
        """
        # Common kwargs for both calls
        call_kwargs = dict(
            IPAddress=ip_address,
            LicenseKey=self.license_key
        )

        # Attempt primary
        try:
            client = Client(self._primary_wsdl, timeout=self._timeout_s)
            # Override endpoint URL if needed:
            # client.set_options(location=self._primary_wsdl.replace('?wsdl','/soap'))
            response = client.service.GetLocationByIP_V4(**call_kwargs)

            # If response invalid or Error.Number == "4", trigger fallback
            if response is None or (hasattr(response, 'Error') and response.Error and response.Error.Number == '4'):
                raise ValueError("Primary returned no result or fatal Error.Number=4")

            return response

        except (WebFault, ValueError, Exception) as primary_ex:
            try:
                client = Client(self._backup_wsdl, timeout=self._timeout_s)
                response = client.service.GetLocationByIP_V4(**call_kwargs)

                if response is None:
                    raise ValueError("Backup returned no result")

                return response

            except (WebFault, Exception) as backup_ex:
                # Raise a combined error if both attempts fail
                msg = (
                    "Both primary and backup endpoints failed.\n"
                    f"Primary error: {str(primary_ex)}\n"
                    f"Backup error: {str(backup_ex)}"
                )
                raise RuntimeError(msg)
    try:
        client = Client(backupURL)
        result = client.service.GetLocationByIP_V4(IPAddress= mIPAddress, LicenseKey=mLicenseKey)
        #Handel response and check for errors
    #If the backup call failed then this will display an error to the screen
    except:
        Label(swin.window, text='Error').pack()
        print (result)

IP Address Validation NodeJS Code Snippet

import { soap } from 'strong-soap';

/**
 * <summary>
 * A class that provides functionality to call the ServiceObjects IP Address Validation SOAP service's GetGeoLocationByIP_V4 endpoint,
 * retrieving geographic location, proxy, host name, and US region information with fallback to a backup endpoint for reliability in live mode.
 * </summary>
 */
class GetGeoLocationByIPV4Soap {
    /**
     * <summary>
     * Initializes a new instance of the GetGeoLocationByIPV4Soap class with the provided input parameters,
     * setting up primary and backup WSDL URLs based on the live/trial mode.
     * </summary>
     * @param {string} IPAddress - The IP address to look up, e.g., "209.85.173.104".
     * @param {string} LicenseKey - Your license key to use the service.
     * @param {boolean} isLive - Value to determine whether to use the live or trial servers.
     * @param {number} timeoutSeconds - Timeout, in seconds, for the call to the service.
     * @throws {Error} Thrown if LicenseKey is empty or null.
     */
    constructor(IPAddress, LicenseKey, isLive = true, timeoutSeconds = 15) {

        this.args = {
            IPAddress,
            LicenseKey
        };

        this.isLive = isLive;
        this.timeoutSeconds = timeoutSeconds;

        this.LiveBaseUrl = "https://sws.serviceobjects.com/GPP/soap.svc?wsdl";
        this.BackupBaseUrl = "https://swsbackup.serviceobjects.com/GPP/soap.svc?wsdl";
        this.TrialBaseUrl = "https://trial.serviceobjects.com/GPP/soap.svc?wsdl";

        this._primaryWsdl = this.isLive ? this.LiveBaseUrl : this.TrialBaseUrl;
        this._backupWsdl = this.isLive ? this.BackupBaseUrl : this.TrialBaseUrl;
    }

    /**
     * <summary>
     * Asynchronously calls the GetGeoLocationByIP_V4 SOAP endpoint, attempting the primary endpoint
     * first and falling back to the backup if the response is invalid (Error.Number == '4') in live mode
     * or if the primary call fails.
     * </summary>
     * <returns type="Promise<IPAVResponse>">A promise that resolves to an IPAVResponse object containing geographic location details or an error.</returns>
     * <exception cref="Error">Thrown if both primary and backup calls fail, with detailed error messages.</exception>
     */
    async getGeoLocationByIPV4() {
        try {
            const primaryResult = await this._callSoap(this._primaryWsdl, this.args);

            if (this.isLive && !this._isValid(primaryResult)) {
                console.warn("Primary returned Error.Number == '4', falling back to backup...");
                const backupResult = await this._callSoap(this._backupWsdl, this.args);
                return backupResult;
            }

            return primaryResult;
        } catch (primaryErr) {
            try {
                const backupResult = await this._callSoap(this._backupWsdl, this.args);
                return backupResult;
            } catch (backupErr) {
                throw new Error(`Both primary and backup calls failed:\nPrimary: ${primaryErr.message}\nBackup: ${backupErr.message}`);
            }
        }
    }

    /**
     * <summary>
     * Performs a SOAP service call to the specified WSDL URL with the given arguments,
     * creating a client and processing the response into an IPAVResponse object.
     * </summary>
     * <param name="wsdlUrl" type="string">The WSDL URL of the SOAP service endpoint (primary or backup).</param>
     * <param name="args" type="Object">The arguments to pass to the GetGeoLocationByIP_V4 method.</param>
     * <returns type="Promise<IPAVResponse>">A promise that resolves to an IPAVResponse object containing the SOAP response data.</returns>
     * <exception cref="Error">Thrown if the SOAP client creation fails, the service call fails, or the response cannot be parsed.</exception>
     */
    _callSoap(wsdlUrl, args) {
        return new Promise((resolve, reject) => {
            soap.createClient(wsdlUrl, { timeout: this.timeoutSeconds * 1000 }, (err, client) => {
                if (err) return reject(err);

                client.GetLocationByIP_V4(args, (err, result) => {
                    const rawData = result?.GetLocationByIP_V4Result;
                    try {
                        if (!rawData) {
                            return reject(new Error("SOAP response is empty or undefined."));
                        }
                        resolve(rawData);
                    } catch (parseErr) {
                        reject(new Error(`Failed to parse SOAP response: ${parseErr.message}`));
                    }
                });
            });
        });
    }

    /**
     * <summary>
     * Checks if a SOAP response is valid by verifying that it exists and either has no Error object
     * or the Error.Number is not equal to '4'.
     * </summary>
     * <param name="response" type="IPAVResponse">The IPAVResponse object to validate.</param>
     * <returns type="boolean">True if the response is valid, false otherwise.</returns>
     */
    _isValid(response) {
        return response && (!response.Error || response.Error.Number !== "4");
    }
}

export { GetGeoLocationByIPV4Soap };