One of the great things about Mullvad is that every WireGuard server comes with a SOCKS5 proxy running on port 1080. That means if you’re connected via WireGuard, you can route your HTTP requests through any of Mullvad’s servers to make the traffic exit from a different location. In this article, I’ll show you a method I’ve been playing around with that lets each browser request go out through a different Mullvad IP address.

This is more for fun/experiment. The practicality of this is questionable. You’re almost certainly going to run into issues on some websites.

Methodology

Here’s the core idea of how this works:

  1. Obtain a list of Mullvad WireGuard servers
  2. Construct the SOCKS5 URLs from these servers’ hostnames. Based on Mullvad’s naming conventions, the SOCKS5 proxy URLs can be constructed like this:
    1. Given a WireGuard relay server’s hostname like us-slc-wg-202
    2. Insert socks5- after wg-
    3. Append .relays.mullvad.net:1080
    4. You get the full SOCKS5 proxy URL us-slc-wg-sock5-202.relays.mullvad.net:1080
  3. Make a PAC script with a FindProxyForURL function that selects a random SOCKS5 proxy from the list for each browser request

When we apply this PAC script in our browser, each request in the browser should go through a random SOCKS5 proxy and exit from a random Mullvad IP address. We can also optionally filter the proxy list by country, latency, or other metrics to achieve other desired effects.

Example

Below is an example of how we can use Mullvad’s Wireguard Server List API to obtain a list of the Mullvad WireGuard relays, filter servers that are in the United States, construct SOCKS5 proxy URLs, and generate a PAC.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import requests

# RELAYS_URL = "https://api.mullvad.net/app/v1/relays"
RELAYS_URL = "https://api.mullvad.net/public/relays/wireguard/v2"

print(
    """function FindProxyForURL(url, host) {
    var proxies = ["""
)

response = requests.get(RELAYS_URL, timeout=5).json()
for relay in response["wireguard"]["relays"]:
    if relay["location"].startswith("us-") and relay["active"] is True:
        print(
            '        "SOCKS5 {}.relays.mullvad.net:1080",'.format(
                relay["hostname"].replace("wg-", "wg-socks5-")
            )
        )

print(
    """    ];
    var i = Math.floor(Math.random() * proxies.length);
    return proxies[i];
}"""
)

The generated PAC file should look something like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
function FindProxyForURL(url, host) {
    var proxies = [
        "SOCKS5 us-atl-wg-socks5-001.relays.mullvad.net:1080",
        "SOCKS5 us-atl-wg-socks5-002.relays.mullvad.net:1080",
        "SOCKS5 us-atl-wg-socks5-201.relays.mullvad.net:1080",
        "SOCKS5 us-atl-wg-socks5-202.relays.mullvad.net:1080",
        "SOCKS5 us-atl-wg-socks5-203.relays.mullvad.net:1080",
        // 150 more entries omitted
    ];
    var i = Math.floor(Math.random() * proxies.length);
    return proxies[i];
}

You can paste this PAC script into something like ZeroOmega, select this profile, and your requests will start to go through random Mullvad SOCKS5 proxies.

Zero Omega PAC Profile

You can verify that things are working by testing examining your IP address against these services:

You can refresh the browser and the request IP should change every time you refresh.

addresses

Filtering and Ranking

Adding all the available proxies to the PAC script is ideal if you want the exit IP address to be as random as possible. However, you may also want to filter the list of proxies in some cases. For instance, let’s say you’re in North America, you can select only proxies that are in North America and have a latency lower than 40 ms to reduce the latency. I wrote a more advanced script with the help of some LLMs as an example:

Click to reveal the Python script
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Script to test latency of Mullvad WireGuard relays and generate a PAC file.
Uses raw sockets for cross-platform ICMP ping functionality.
"""

import argparse
import socket
import statistics
import sys
import time
from concurrent.futures import ThreadPoolExecutor
from typing import List, TypedDict

import requests
from loguru import logger


class Relay(TypedDict):
    hostname: str
    location: str
    socks5: str


class RelayResult(TypedDict):
    relay: Relay
    latency: float


def ping_host(hostname: str, ping_count: int, ping_timeout: int) -> float:
    try:
        try:
            ip_address = socket.gethostbyname(hostname)
        except socket.gaierror:
            return float("inf")

        rtts = []
        for _ in range(ping_count):
            try:
                start = time.time()
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                s.settimeout(ping_timeout)
                s.connect((ip_address, 1080))
                s.close()
                rtts.append((time.time() - start) * 1000)
            except (socket.timeout, socket.error):
                rtts.append(float("inf"))

        valid_rtts = [rtt for rtt in rtts if rtt != float("inf")]
        return statistics.mean(valid_rtts) if valid_rtts else float("inf")
    except Exception as e:
        logger.error(f"Error pinging {hostname}: {str(e)}")
        return float("inf")


def get_relays(relays_url: str, location_prefixes: List[str]) -> List[Relay]:
    try:
        response = requests.get(relays_url, timeout=5).json()
        relays = []
        for relay in response["wireguard"]["relays"]:
            if (
                any(
                    relay["location"].startswith(prefix) for prefix in location_prefixes
                )
                and relay["active"] is True
            ):
                host = "{}.relays.mullvad.net".format(
                    relay["hostname"].replace("wg-", "wg-socks5-")
                )
                relays.append(
                    {
                        "hostname": host,
                        "location": relay["location"],
                        "socks5": f"SOCKS5 {host}:1080",
                    }
                )
        return relays
    except Exception as e:
        logger.error(f"Failed to fetch relays: {str(e)}")
        return []


def measure_latency(
    relays: List[Relay], ping_count: int, ping_timeout: int
) -> List[RelayResult]:
    results = []
    with ThreadPoolExecutor(max_workers=10) as executor:
        futures = []
        for relay in relays:
            futures.append(
                (
                    relay,
                    executor.submit(
                        ping_host, relay["hostname"], ping_count, ping_timeout
                    ),
                )
            )

        processed = 0
        total = len(relays)
        for relay, future in futures:
            latency = future.result()
            results.append({"relay": relay, "latency": latency})
            processed += 1
            if latency == float("inf"):
                logger.warning(f"[{processed}/{total}] {relay['hostname']}: timed out")
            else:
                logger.info(
                    f"[{processed}/{total}] {relay['hostname']}: {latency:.2f} ms"
                )

    results.sort(key=lambda x: x["latency"])
    return results


def generate_pac(ranked_relays: List[RelayResult]) -> str:
    pac_content = """function FindProxyForURL(url, host) {
    var proxies = [
"""
    for result in ranked_relays:
        pac_content += f'        "{result["relay"]["socks5"]}",\n'
    pac_content += """    ];
    var i = Math.floor(Math.random() * proxies.length);
    return proxies[i];
}"""
    return pac_content


def main() -> int:
    parser = argparse.ArgumentParser(
        description="Mullvad WireGuard Relay Latency Tester and PAC Generator"
    )
    parser.add_argument(
        "--relays-url",
        default="https://api.mullvad.net/public/relays/wireguard/v2",
        help="URL for Mullvad relays",
    )
    parser.add_argument(
        "--pac-file", default="mullvad_proxy.pac", help="Output PAC file"
    )
    parser.add_argument(
        "--ping-count", default=5, type=int, help="Number of connectivity checks"
    )
    parser.add_argument(
        "--ping-timeout",
        default=1,
        type=int,
        help="Timeout (seconds) for each connectivity check",
    )
    parser.add_argument(
        "--max-latency",
        default=None,
        type=float,
        help="Ignore relays with latency above this threshold (ms)",
    )
    parser.add_argument(
        "--location-prefixes",
        default=[""],
        nargs="+",
        help="Location prefixes to filter relays",
    )
    args = parser.parse_args()

    logger.info(f"Using location prefixes: {args.location_prefixes}")
    logger.info("Fetching relays...")
    relays = get_relays(args.relays_url, args.location_prefixes)
    if not relays:
        logger.error("No relays found!")
        return 1

    logger.info("Measuring latency...")
    ranked_relays = measure_latency(relays, args.ping_count, args.ping_timeout)
    working_relays = [r for r in ranked_relays if r["latency"] != float("inf")]

    if args.max_latency is not None:
        working_relays = [r for r in working_relays if r["latency"] <= args.max_latency]

    logger.info(
        f"Found {len(working_relays)} working relays out of {len(relays)} total."
    )
    if not working_relays:
        logger.error("No working relays found under the specified conditions!")
        return 2

    logger.info("Sorted relays by latency (lowest first):")
    for i, result in enumerate(working_relays):
        logger.info(
            f"{i + 1}. {result['relay']['hostname']}: {result['latency']:.2f} ms"
        )

    logger.info("Generating PAC file content...")
    pac_content = generate_pac(working_relays)

    logger.info(f"Saving PAC file to {args.pac_file}")
    try:
        with open(args.pac_file, "w", encoding="utf-8") as f:
            f.write(pac_content)
        logger.success(f"PAC file saved with {len(working_relays)} working relays.")
    except Exception as e:
        logger.error(f"Failed to save PAC file: {str(e)}")
        return 3

    return 0


if __name__ == "__main__":
    start_time = time.time()
    exit_code = 0
    try:
        exit_code = main()
    except Exception as e:
        logger.error(f"Script failed: {str(e)}")
        exit_code = 4
    finally:
        logger.info(f"Total execution time: {time.time() - start_time:.2f} seconds")
    sys.exit(exit_code)

Here’s how you can make a PAC script with the script above that includes all servers in the United States and Canada and have a latency lower than 40 ms:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
$ python make_pac.py --max-latency 40 --location-prefixes us- ca-
2025-04-13 04:41:52.911 | INFO     | __main__:main:168 - Using location prefixes: ['us-', 'ca-']
2025-04-13 04:41:52.911 | INFO     | __main__:main:169 - Fetching relays...
2025-04-13 04:41:53.453 | INFO     | __main__:main:175 - Measuring latency...
2025-04-13 04:41:53.596 | INFO     | __main__:measure_latency:112 - [1/181] ca-mtr-wg-socks5-001.relays.mullvad.net: 69.44 ms
2025-04-13 04:41:53.596 | INFO     | __main__:measure_latency:112 - [2/181] ca-mtr-wg-socks5-002.relays.mullvad.net: 110.92 ms
2025-04-13 04:41:53.597 | INFO     | __main__:measure_latency:112 - [3/181] ca-mtr-wg-socks5-003.relays.mullvad.net: 32.32 ms
2025-04-13 04:41:53.597 | INFO     | __main__:measure_latency:112 - [4/181] ca-mtr-wg-socks5-004.relays.mullvad.net: 126.76 ms
2025-04-13 04:41:53.597 | INFO     | __main__:measure_latency:112 - [5/181] ca-tor-wg-socks5-001.relays.mullvad.net: 41.35 ms
.
.
.
2025-04-13 04:41:58.565 | INFO     | __main__:main:182 - Found 5 working relays out of 181 total.
2025-04-13 04:41:58.565 | INFO     | __main__:main:189 - Sorted relays by latency (lowest first):
2025-04-13 04:41:58.565 | INFO     | __main__:main:191 - 1. us-lax-wg-socks5-405.relays.mullvad.net: 30.56 ms
2025-04-13 04:41:58.565 | INFO     | __main__:main:191 - 2. us-nyc-wg-socks5-501.relays.mullvad.net: 30.65 ms
2025-04-13 04:41:58.565 | INFO     | __main__:main:191 - 3. us-qas-wg-socks5-101.relays.mullvad.net: 32.19 ms
2025-04-13 04:41:58.565 | INFO     | __main__:main:191 - 4. us-lax-wg-socks5-407.relays.mullvad.net: 32.23 ms
2025-04-13 04:41:58.565 | INFO     | __main__:main:191 - 5. ca-mtr-wg-socks5-003.relays.mullvad.net: 32.32 ms
2025-04-13 04:41:58.565 | INFO     | __main__:main:195 - Generating PAC file content...
2025-04-13 04:41:58.565 | INFO     | __main__:main:198 - Saving PAC file to mullvad_proxy.pac
2025-04-13 04:41:58.565 | SUCCESS  | __main__:main:202 - PAC file saved with 17 working relays.
2025-04-13 04:41:58.565 | INFO     | __main__:<module>:219 - Total execution time: 5.66 seconds

The PAC file will contain all the proxies that match the given criteria, sorted from the lowest latency to the highest latency:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
function FindProxyForURL(url, host) {
  var proxies = [
    "SOCKS5 us-lax-wg-socks5-405.relays.mullvad.net:1080",
    "SOCKS5 us-nyc-wg-socks5-501.relays.mullvad.net:1080",
    "SOCKS5 us-qas-wg-socks5-101.relays.mullvad.net:1080",
    "SOCKS5 us-lax-wg-socks5-407.relays.mullvad.net:1080",
    "SOCKS5 ca-mtr-wg-socks5-003.relays.mullvad.net:1080",
  ];
  var i = Math.floor(Math.random() * proxies.length);
  return proxies[i];
}