---
title: "DMA Code from an IP Address: Find a Visitor's TV Market"
slug: "/tutorials/dma-code-from-ip-address"
description: "Get the Nielsen DMA code for a US IP address with the IPGeolocation.io API. See the request, the response, how DMA differs from ZIP, and edge cases."
---

# How to Get a DMA Code from an IP Address

By [Daud Ahmad](https://www.linkedin.com/in/daudahmad0303) Software Engineer

Posted on November 23, 2026 | 10 min read

![How to Get a DMA Code from an IP Address](https://blogs.ipgeolocation.io/blogs-site/content/images/size/w1600/format/webp/2026/11/dma-code-from-ip-address.png)

A DMA code is the three-digit number for one of the [210 US television markets](https://www.nielsen.com/dma-regions/) Nielsen defines, and you can get it from an IP address with one IPGeolocation.io lookup. Add `include=dma_code` to the request and the response carries `location.dma_code`: 504 for an address in Philadelphia. Outside the United States, the field comes back empty.

* * *

## TL;DR

To get a DMA code from an IP address, call IPGeolocation.io's `/v3/ipgeo` endpoint with `include=dma_code` and a paid-plan key, then read `location.dma_code`, a three-digit string such as `"504"`. The ZIP code sits in the same `location` object.

*   The DMA code adds no credits: the lookup costs 1 credit, the same as one without it.
*   A free-plan key gets HTTP 401 for `include=dma_code`. The ZIP code (`location.zipcode`) comes back on every plan.
*   `dma_code` is an empty string for addresses outside the US, including Puerto Rico and Guam, which return their own country codes.
*   `zipcode` can be five digits or ZIP+4 (`08854-8089`). Store both fields as strings.
*   The bulk endpoint takes up to 50,000 IPs per request and charges only for valid entries.

* * *

## What a DMA code tells you

DMA stands for Designated Market Area. Nielsen splits the country into 210 of them, each "a group of counties and zip codes" where the local stations hold most of the TV viewing. Together they cover the continental US, Hawaii, and parts of Alaska, and Nielsen owns the boundaries. Each market has a three-digit code, which [Adobe's analytics docs](https://experienceleague.adobe.com/en/docs/analytics/components/dimensions/us-dma) describe as "not a zip code, but rather the DMA code from Nielsen."

The code names a market, and a market is bigger than a city or a ZIP code. It can also cross a state line. In our tests, an address on Rutgers University's network in Piscataway, New Jersey, comes back with `state_code` US-NJ and `dma_code` 501, the New York market. A campaign aimed at New York TV viewers should count that visitor, even though a state-based report would put them in New Jersey.

![Diagram: IP 128.6.0.1 in ZIP 08854, Middlesex County, New Jersey, inside DMA 501, which spans two states](https://blogs.ipgeolocation.io/blogs-site/content/images/2026/11/dma-state-county-zip-nesting.webp)

The response carries the code, not the market's name. Names come with Nielsen's licensed DMA data, and ad platforms publish their own lists: Microsoft's [Xandr DMA service](https://learn.microsoft.com/en-us/xandr/digital-platform-api/designated-market-area-service), for example, returns code 504 with the name "Philadelphia PA". IPGeolocation.io's data team assigns each IP range its code from the range's location, following the way Nielsen's own system assigns regions to markets.

* * *

## DMA code vs ZIP code

A DMA code is not a ZIP code. The two answer different questions about the same address, and one IPGeolocation.io lookup returns both.

|     | DMA Code | ZIP Code |
| --- | --- | --- |
| Defined by | Nielsen, for TV audience measurement | The US Postal Service, for mail delivery |
| What it covers | A TV market built from groups of counties | A delivery area, which can cross county lines |
| Example | `501` (New York market) | `08854` (Piscataway, NJ) |
| Field | `location.dma_code` | `location.zipcode` |
| Format | Three digits, sent as a string | Five digits or ZIP+4, sent as a string |

Because a ZIP code isn't drawn around counties, one ZIP can touch two DMAs. The IP lookup returns one DMA code for the IP's own range, so you don't have to choose between them. Keep the ZIP for what it's good at: local offers, store distance, and finer reporting inside a market.

* * *

## Who uses DMA codes, and what for

Nielsen's own [list of uses for DMA data](https://www.nielsen.com/dma-regions/) covers local advertising, selling ad time by TV market, picking local research samples, and segmenting data by market. An IP-based DMA code brings the same geography to traffic you already have: page views, sign-ups, ad clicks, and app sessions.

![Four uses of DMA codes: TV and streaming, ad platforms, web analytics, and marketers, retailers, and researchers](https://blogs.ipgeolocation.io/blogs-site/content/images/2026/11/dma-code-use-cases.webp)

* * *

### 1. TV and streaming

Stations sell ad time market by market, so a streaming service or a station's website that tags each session with a DMA code can report its audience in the same units its advertisers buy.

* * *

### 2. Ad platforms and programmatic buying

For DMA targeting, Google Ads lists [Nielsen DMA regions as a location target type](https://support.google.com/google-ads/answer/1722075?hl=en), and Xandr exposes DMA IDs for campaign targeting. When your own click and conversion logs carry the same code, you can check results against the markets a campaign targeted, without a second geography to reconcile.

* * *

### 3. Web and product analytics

Adobe Analytics derives a "US DMA" dimension from the visitor's IP address and reports values such as "New York (501)". The same lookup gives you that dimension in your own warehouse, next to the events you already store.

* * *

### 4. Marketers, retailers, and researchers

Regional budgets, store territories, and survey quotas often follow TV markets. A DMA code on each lead or order lets a team set sales in market 504 against what it spent on ads there, then do the same for every other market.

* * *

## Before you start

*   You have a paid-plan IPGeolocation.io API key in the `IPGEO_API_KEY` environment variable. To check DMA data before buying, ask our [support team](https://ipgeolocation.io/contact.html) or live chat for a free trial of a paid plan.
*   You have Python 3.10 or later and the official library: `pip install ipgeolocationio`.
*   You have curl.
*   In a web app, you know which IP to look up. Read the visitor's address the safe way behind a proxy ([how to get a visitor's real IP address](https://ipgeolocation.io/guides/get-real-client-ip-address)), and keep the key on your server ([keep your API key out of browser code](https://ipgeolocation.io/tutorials/secure-api-key-before-production)).

* * *

## Step 1: Request the DMA code with curl

A DMA code lookup by IP takes one request. The `include` parameter adds the DMA module, and `fields` trims the response to the values this tutorial uses.

```bash
curl -s "https://api.ipgeolocation.io/v3/ipgeo?apiKey=$IPGEO_API_KEY&ip=107.161.145.197&include=dma_code&fields=location.city,location.state_code,location.district,location.zipcode,location.dma_code"
```

Expected output (run on November 19, 2026; the response header showed `X-Credits-Charged: 1`):

```json
{"ip":"107.161.145.197","location":{"state_code":"US-PA","district":"Philadelphia County","city":"Philadelphia","dma_code":"504","zipcode":"19102"}}
```

`district` is the county, the unit DMAs are built from, and `dma_code` is the market. Listing `location.dma_code` in `fields` without `include=dma_code` doesn't add the code, so keep both parameters. IPv6 addresses work the same way, and the [IP Geolocation API documentation](https://ipgeolocation.io/documentation/ip-location-api.html) lists every field and parameter.

![IPGeolocation.io response for 107.161.145.197 with dma_code 504, zipcode 19102, and county highlighted](https://blogs.ipgeolocation.io/blogs-site/content/images/2026/11/dma-code-response-fields.webp)

If the key is on the free plan, the API answers with HTTP 401 and this body:

```json
{"message":"DMA code lookup is not supported on your subscription. This feature is available on Paid subscriptions only."}
```

To check a single address by hand, no key needed, open its lookup page on our site: [the lookup page for 107.161.145.197](https://ipgeolocation.io/what-is-my-ip/107.161.145.197) shows the same DMA code, 504, under Additional fields in its Geolocation tab. Swap any IP into the end of that address.

* * *

## Step 2: Read the DMA code and ZIP code in Python

The script below uses [the official IPGeolocation.io Python library](https://ipgeolocation.io/documentation/ip-geolocation-api-python-sdk.html) to look up three addresses and turn each response into values you can store.

```python
import os
import sys

from ipgeolocation import (
    IpGeolocationClient,
    IpGeolocationClientConfig,
    IpGeolocationException,
    LookupIpGeolocationRequest,
    UnauthorizedException,
)


def lookup_market(client, ip):
    """Return the DMA code and ZIP code the API has for one IP address."""
    response = client.lookup_ip_geolocation(
        LookupIpGeolocationRequest(
            ip=ip,
            include=["dma_code"],  # an add-on: listing it in fields alone won't return it
            fields=["location.country_code2", "location.dma_code", "location.zipcode"],
        )
    )
    location = response.data.location
    if location is None:
        return {"ip": ip, "dma_code": None, "zipcode": None, "zip5": None}

    zipcode = location.zipcode or None
    is_us = location.country_code2 == "US"
    return {
        "ip": ip,
        # Outside Nielsen's US markets the API sends "". Store None so a
        # report never counts an empty string as a market.
        "dma_code": location.dma_code or None,
        # Keep ZIP codes as strings: "08854" loses its leading zero as a number.
        "zipcode": zipcode,
        # US values can be ZIP+4 ("08854-8089"); the first five digits are the ZIP.
        "zip5": zipcode[:5] if zipcode and is_us else None,
    }


def main():
    api_key = os.environ.get("IPGEO_API_KEY")
    if not api_key:
        sys.exit("Set IPGEO_API_KEY to a paid-plan IPGeolocation.io API key.")

    with IpGeolocationClient(IpGeolocationClientConfig(api_key=api_key)) as client:
        for ip in ["107.161.145.197", "128.6.0.1", "91.128.103.196"]:
            try:
                print(lookup_market(client, ip))
            except UnauthorizedException as error:
                # A free-plan key gets 401 for include=dma_code.
                sys.exit(f"401 Unauthorized: {error.api_message}")
            except IpGeolocationException as error:
                print(f"{ip}: lookup failed ({error})")


if __name__ == "__main__":
    main()
```

Expected output:

```text
{'ip': '107.161.145.197', 'dma_code': '504', 'zipcode': '19102', 'zip5': '19102'}
{'ip': '128.6.0.1', 'dma_code': '501', 'zipcode': '08854-8089', 'zip5': '08854'}
{'ip': '91.128.103.196', 'dma_code': None, 'zipcode': '164 40', 'zip5': None}
```

The second address shows both details worth handling: a ZIP+4 value and a leading zero. The third is in Stockholm, so it has a postal code but no DMA code. If `IPGEO_API_KEY` is missing, the script stops with the message in `main()`; with a free-plan key, it stops with the API's 401 message from Step 1.

* * *

## Step 3: Count visits by DMA and leave out datacenter traffic

107.161.145.197 resolves to Philadelphia, market 504, but it belongs to a hosting provider: it's a server in a data center, not a viewer. IPGeolocation.io's network fields show that. `asn.type` and `company.type` read `HOSTING` for it, and both fields are part of the paid-plan response at no extra credit. The other values are `ISP`, `BUSINESS`, `EDUCATION`, and `GOVERNMENT`; only `HOSTING` marks datacenter space.

This script sends a list of IPs to the bulk endpoint, sets aside datacenter and non-US addresses, and counts the rest by market:

```python
import os
import sys
from collections import Counter

from ipgeolocation import (
    BulkLookupError,
    BulkLookupIpGeolocationRequest,
    IpGeolocationClient,
    IpGeolocationClientConfig,
    IpGeolocationException,
)

# asn.type and company.type come with the base lookup, so the data-center
# check below adds no credits.
FIELDS = ["location.dma_code", "asn.type", "company.type"]


def market_counts(client, ips):
    """Count IPs per DMA code, leaving out non-US and data-center addresses."""
    response = client.bulk_lookup_ip_geolocation(
        BulkLookupIpGeolocationRequest(ips=ips, include=["dma_code"], fields=FIELDS)
    )
    counts, skipped, errors = Counter(), Counter(), []
    for result in response.data:  # one result per input IP, in the same order
        if isinstance(result, BulkLookupError):
            skipped["lookup error"] += 1
            errors.append(result.error.message)  # bogon, invalid, or not allowed
            continue

        data = result.data
        dma = data.location.dma_code if data.location else ""
        network_types = {
            data.asn.type if data.asn else None,
            data.company.type if data.company else None,
        }
        if not dma:
            skipped["no DMA code (outside US markets)"] += 1
        elif "HOSTING" in network_types:
            skipped["data-center address"] += 1
        else:
            counts[dma] += 1
    return counts, skipped, errors, response.metadata.credits_charged


def main():
    api_key = os.environ.get("IPGEO_API_KEY")
    if not api_key:
        sys.exit("Set IPGEO_API_KEY to a paid-plan IPGeolocation.io API key.")

    ips = ["107.161.145.197", "128.6.0.1", "91.128.103.196", "10.0.0.1"]
    with IpGeolocationClient(IpGeolocationClientConfig(api_key=api_key)) as client:
        try:
            counts, skipped, errors, credits = market_counts(client, ips)
        except IpGeolocationException as error:
            sys.exit(f"Bulk lookup failed: {error}")

    print("Visits by DMA:", dict(counts))
    print("Left out:", dict(skipped))
    for message in errors:
        print("  ", message)
    print("Credits charged:", credits)


if __name__ == "__main__":
    main()
```

Expected output:

```text
Visits by DMA: {'501': 1}
Left out: {'data-center address': 1, 'no DMA code (outside US markets)': 1, 'lookup error': 1}
   '10.0.0.1' is a bogon IP address.
Credits charged: 3
```

Four IPs went in and three credits were charged: the private address 10.0.0.1 comes back as an error message and isn't billed. Only the Rutgers address counts toward a market. With a free-plan key, the script counts nothing and prints the "not supported on your subscription" message from Step 1 for each IP. In production, look up each distinct IP once, cache the result, join it back to your visit rows, and split lists longer than 50,000.

We'd run the network check first because it costs nothing extra. When a report also has to drop VPN, proxy, and Tor traffic, add `include=security`: it adds 2 credits per IP and returns those flags with a threat score. The tutorial on [checking whether an IP is a VPN, proxy, or Tor exit](https://ipgeolocation.io/tutorials/check-ip-for-vpn-proxy-tor) shows the fields, and the same data is available on its own from the [Proxy & VPN Detection API](https://ipgeolocation.io/ip-security-api.html).

* * *

## When the DMA code is empty or doesn't match the person

An empty `dma_code` means the API has no US television market for the address. In our tests, addresses in Canada, Mexico, Puerto Rico, Guam, the US Virgin Islands, and American Samoa all returned an empty string, and the territories came back with their own country codes (PR, GU, VI, AS) rather than US. Treat an empty value as "no market" whatever the country code says, rather than inferring a market from the country.

A DMA code can also be correct for the network and still miss the person. Mobile carriers route traffic through regional gateways, VPNs and relays exit far from the user, and corporate networks send remote staff through head office. These limits apply to IP data from any provider. IPGeolocation.io's security data flags VPN, proxy, and relay exits, and [why an IP location can be wrong](https://ipgeolocation.io/help/why-is-my-ip-location-wrong) walks through each case. If you find an address with the wrong DMA code, report it through our [contact page](https://ipgeolocation.io/contact.html) and the data team will check it.

* * *

## DMA codes and more from one IPGeolocation.io lookup

IPGeolocation.io returns the DMA code as one field in a full IP lookup. The same request can carry geolocation (from country down to ZIP code, coordinates, and accuracy radius), security data, ASN details, the company behind the address, abuse contact data, time zone, and user agent data. Every plan gets its results from the same database, built in our own pipeline with active measurement (we ping and traceroute networks from our own measurement points) and refreshed daily. Here's [how our IP geolocation data is built](https://ipgeolocation.io/blog/how-ip-geolocation-data-is-built).

For offline work, the [IP to Location database](https://ipgeolocation.io/ip-geolocation-database.html) in the Geo Advanced tier carries `dma_code` next to `zip_code`, so a log pipeline can tag millions of rows without calling the API. For plans and credits, see the [pricing page](https://ipgeolocation.io/pricing.html).

## FAQ

### What is a DMA code?

**Answer:** A DMA code is a three-digit number that identifies one of the 210 US television markets Nielsen defines, such as 501 for New York or 504 for Philadelphia. Each market is a group of counties where the local stations hold most of the viewing.

### Is a DMA the same as a ZIP code?

**Answer:** No. A DMA is a TV market built from groups of counties, while a ZIP code is a Postal Service delivery area that can cross county lines. One IPGeolocation.io lookup returns both, as `location.dma_code` and `location.zipcode`.

### How do I find my own DMA code?

**Answer:** Open [IPGeolocation.io's What is my IP page](https://ipgeolocation.io/what-is-my-ip): it shows the DMA code for your connection's IP address under Additional fields in the Geolocation tab. For any other address, add it to the end of the page's address, as in ipgeolocation.io/what-is-my-ip/8.8.8.8, which shows 807. On a VPN, you see the VPN exit's market instead of yours.

### Does the DMA code work outside the United States?

**Answer:** No. DMAs cover US television markets only, so `dma_code` is an empty string for addresses in other countries. Addresses in Puerto Rico, Guam, the US Virgin Islands, and American Samoa return their own country codes and an empty `dma_code` too.

### Is the DMA code free with IPGeolocation.io?

**Answer:** No, the DMA code needs a paid plan, though it adds no credits to the 1-credit lookup. The free Developer plan gives you 1,000 credits a day for life, with no credit card, and its lookups include the ZIP code. Paid plans add more data, such as accuracy radius, company, network, and security data, and start at $19 a month for 150,000 credits.

### Related Tutorials

[![How to Run a Bulk IP Lookup on a CSV Without Losing Rows](https://blogs.ipgeolocation.io/blogs-site/content/images/size/w1000/format/webp/2026/11/visual-0-feature-option-g-before-and-after.webp)](https://ipgeolocation.io/tutorials/bulk-ip-lookup-csv)

[How to Run a Bulk IP Lookup on a CSV Without Losing Rows](https://ipgeolocation.io/tutorials/bulk-ip-lookup-csv)

A Python script that sends the IP addresses from a 10,000-row CSV to the IPGeolocation.io bulk API in one request, gives every row a status, writes the rows to retry to their own file, and resumes where it stopped.

Posted on December 1, 2026

By [Abdullah Afzal](https://www.linkedin.com/in/abdullah-a-08ba162b7?utm_source=share&utm_campaign=share_via&utm_content=profile&utm_medium=android_app)

[Read More: How to Run a Bulk IP Lookup on a CSV Without Losing Rows](https://ipgeolocation.io/tutorials/bulk-ip-lookup-csv)

[![How to Read an MMDB File in Python, Go, Node.js, and Java](https://blogs.ipgeolocation.io/blogs-site/content/images/size/w1000/format/webp/2026/10/visual-0-feature-option-f-search-tree.webp)](https://ipgeolocation.io/tutorials/how-to-read-mmdb-file)

[How to Read an MMDB File in Python, Go, Node.js, and Java](https://ipgeolocation.io/tutorials/how-to-read-mmdb-file)

Open an MMDB file once, look up IPv4 and IPv6 addresses, and handle missing and malformed input in Python, Go, Node.js, and Java. Every program is tested against IPGeolocation.io's free sample files, with the output it prints.

Posted on November 30, 2026

By [Abdullah Afzal](https://www.linkedin.com/in/abdullah-a-08ba162b7?utm_source=share&utm_campaign=share_via&utm_content=profile&utm_medium=android_app)

[Read More: How to Read an MMDB File in Python, Go, Node.js, and Java](https://ipgeolocation.io/tutorials/how-to-read-mmdb-file)

[![How to Automate IPGeolocation.io Database Updates](https://blogs.ipgeolocation.io/blogs-site/content/images/size/w1000/format/webp/2026/10/visual-0-feature-option-a-daily-cycle.webp)](https://ipgeolocation.io/tutorials/automate-ipgeolocation-database-updates)

[How to Automate IPGeolocation.io Database Updates](https://ipgeolocation.io/tutorials/automate-ipgeolocation-database-updates)

One Bash script that checks IPGeolocation.io's status endpoint once a day, installs a new database release only after its signature and checksums pass, and makes your application load it.

Posted on November 29, 2026

By [Abdullah Afzal](https://www.linkedin.com/in/abdullah-a-08ba162b7?utm_source=share&utm_campaign=share_via&utm_content=profile&utm_medium=android_app)

[Read More: How to Automate IPGeolocation.io Database Updates](https://ipgeolocation.io/tutorials/automate-ipgeolocation-database-updates)

[![Get Only the IP Data You Need With fields and excludes](https://blogs.ipgeolocation.io/blogs-site/content/images/size/w1000/format/webp/2026/10/ip-geolocation-api-fields-and-excludes.png)](https://ipgeolocation.io/tutorials/ip-geolocation-api-fields-and-excludes)

[Get Only the IP Data You Need With fields and excludes](https://ipgeolocation.io/tutorials/ip-geolocation-api-fields-and-excludes)

fields keeps only the response paths you list, and excludes removes the ones you name. Recipes for each kind of IP data, tested on the Developer plan and paid keys, with curl, Python, and Node.js.

Posted on November 25, 2026

By [Daud Ahmad](https://www.linkedin.com/in/daudahmad0303)

[Read More: Get Only the IP Data You Need With fields and excludes](https://ipgeolocation.io/tutorials/ip-geolocation-api-fields-and-excludes)

[![Log the Credits Each Request Uses with X-Credits-Charged](https://blogs.ipgeolocation.io/blogs-site/content/images/size/w1000/format/webp/2026/11/0-log-credits-x-credits-charged.png)](https://ipgeolocation.io/tutorials/log-x-credits-charged)

[Log the Credits Each Request Uses with X-Credits-Charged](https://ipgeolocation.io/tutorials/log-x-credits-charged)

Every successful IPGeolocation.io response tells you what it cost in the X-Credits-Charged header. Log it with the feature that made the call, total it by day, and get an alert when a call's cost changes or a feature passes its budget, in Python or Node.js.

Posted on November 24, 2026

By Abdul Mateen

[Read More: Log the Credits Each Request Uses with X-Credits-Charged](https://ipgeolocation.io/tutorials/log-x-credits-charged)

[![Auto-Detect Country Code and Time Zone on Signup Forms](https://blogs.ipgeolocation.io/blogs-site/content/images/size/w1000/format/webp/2026/11/auto-detect-country-code-signup-form-1.png)](https://ipgeolocation.io/tutorials/auto-detect-country-code-signup-form)

[Auto-Detect Country Code and Time Zone on Signup Forms](https://ipgeolocation.io/tutorials/auto-detect-country-code-signup-form)

Pre-fill a signup form's country, phone dial code, and time zone from one IP lookup on your server, then let the browser and the visitor correct them. Tested Node.js and intl-tel-input code.

Posted on November 3, 2026

By [Daud Ahmad](https://www.linkedin.com/in/daudahmad0303)

[Read More: Auto-Detect Country Code and Time Zone on Signup Forms](https://ipgeolocation.io/tutorials/auto-detect-country-code-signup-form)
