Inspect SMS Links in Python Without Opening Them11 min read2,258 words

Inspect SMS Links in Python Without Opening Them

Learn how to parse an SMS link locally with Python, spot misleading hosts and IDNs, and understand why link inspection is a clue—not proof a text is safe.

inspect SMS links in PythonSMS link safetyPython URL parsingphishing text messagesIDN homograph attacks
Inspect SMS Links in Python Without Opening Them

Before You Tap: Inspect an SMS Link with Python

A text saying your prescription is ready might be legitimate. Pharmacies send collection reminders, and a store locator can be normal. But the brand name in the message doesn't prove who actually sent it, and a link that looks right at a glance can still point somewhere else.

You don't need to open a link to learn a few useful things. Python's standard library can parse a URL locally and show you the hostname, whether the address uses HTTPS, and a handful of patterns that are worth a closer look. What it can't do is verify the sender, confirm whether a site is malicious, or predict what happens after the page loads.

This guide walks through a small Python script, explains what the output means, and shows a safer way to handle an unexpected prescription text. The sample messages and domains are invented. The script makes no network requests and doesn't check any real phone number or pharmacy.

SMS messages are easy to copy and easy to fake. "Your prescription is ready" could be a routine reminder, an honest mistake, or part of a push to get you to visit a fraudulent page. Sender names and phone numbers are also weak evidence - caller ID and text sender details can be spoofed. Even if the message mentions a real pharmacy, that still doesn't prove the pharmacy sent it.

The URL itself has a more structured form. A browser uses the hostname in the URL to find the destination site, and that hostname can be compared with a domain you already trust (for example, something on a receipt or in an app you installed yourself). It's a practical check because people tend to skim URLs left to right and overvalue the familiar words near the start.

Consider these examples:

  • In https://chemist.example@collect-rx.test/locator, the hostname is collect-rx.test. The text before @ is user information, not the site name.
  • stores.chemist.example is a subdomain of chemist.example. By contrast, chemist-example.test is a different domain that just happens to look similar.
  • A hostname with accented or non-Latin characters may appear in ASCII form starting with xn--. The "looks familiar" character might not be the one you think it is.
  • A bare IP address, such as 192.0.2.44, doesn't tell you who runs the server.

These observations are clues, not proof. HTTPS protects the connection between your device and the host listed in the URL, but it doesn't prove the site is run by the pharmacy you expected. An unfamiliar domain isn't automatically a scam - and a familiar domain can still be used in a deceptive message. The useful question is simpler: does this hostname match a domain you already know should be involved?

That comparison works best if you build your trusted list before you get a suspicious text. Copy the domain from a receipt, a previous letter, or an app you already use. Don't take the "expected" domain from the message you're checking - that turns the check into a self-fulfilling loop.

The script below uses only Python's standard library. It does not make a request, follow a redirect, load a web page, or contact any domain. It extracts tokens that look like URL-shaped strings from sample messages, parses each one with urllib.parse.urlsplit, and then compares the hostname with a short list of example domains.

The .example and .test domains are reserved for documentation and testing. They're placeholders, not real pharmacy addresses. Replace the known domains only with values you've verified independently. For real use, inspect one copied message at a time, and don't paste personal information into scripts or online tools you don't trust.

import ipaddress

from urllib.parse import urlsplit

KNOWN = ['chemist.example', 'surgery.example']

def find_links(text):

candidates = []

for token in text.split():

token = token.rstrip('.,;:!?)]')

if token.startswith(('http://', 'https://')) or '.' in token:

candidates.append(token)

return candidates

def edit_distance(a, b):

previous = list(range(len(b) + 1))

for i, char_a in enumerate(a, 1):

current = [i]

for j, char_b in enumerate(b, 1):

current.append(min(

previous[j] + 1,

current[j - 1] + 1,

previous[j - 1] + (char_a != char_b),

))

previous = current

return previous[-1]

def inspect(raw):

parts = urlsplit(raw if '://' in raw else 'http://' + raw)

host = (parts.hostname or '').rstrip('.')

flags = []

if '://' not in raw:

flags.append('no scheme; the phone or browser may guess one')

elif parts.scheme != 'https':

flags.append('not HTTPS')

if parts.username is not None:

flags.append('text before @ is a username, not the site')

try:

ipaddress.ip_address(host)

flags.append('bare IP address instead of a hostname')

except ValueError:

pass

if not host.isascii():

encoded = host.encode('idna').decode()

flags.append('non-ASCII hostname; IDNA form is ' + encoded)

if parts.port:

flags.append('explicit port ' + str(parts.port))

known = next(

(domain for domain in KNOWN

if host == domain or host.endswith('.' + domain)),

None,

)

if known:

verdict = 'inside ' + known

else:

verdict = 'not a domain you listed'

label = host.split('.')[-2] if host.count('.') else host

for domain in KNOWN:

expected = domain.split('.')[0]

distance = edit_distance(label, expected)

if 0 < distance <= 2:

flags.append(

label + ' is ' + str(distance) +

' edit(s) from ' + expected

)

elif expected in label and label != expected:

flags.append(

'contains ' + expected + ' but is a different domain'

)

return host, verdict, flags

messages = [

'Prescription ready. Store finder: '

'https://stores.chemist.example/riverside',

'Find your store: '

'https://chemist.example@collect-rx.test/locator',

'Locate branch: http://chemist-example.test/find?b=12',

'Ready to collect: https://chémist.example/store',

'Collect now: https://sh.test/r8Kq2',

'Details: 192.0.2.44/rx',

]

for number, message in enumerate(messages, 1):

for link in find_links(message):

host, verdict, flags = inspect(link)

print(str(number) + '. ' + link)

print(' host: ' + host + ' -> ' + verdict)

for flag in flags:

print(' - ' + flag)

This script is meant as a reading aid, not a production URL validator. The token extractor is intentionally simple: it may miss links written in unusual formats, and it can also treat unrelated text containing a dot as a candidate. If you adapt it, test it against the formats you expect instead of assuming it catches every URL in every message.

The hostname check is also intentionally modest. It compares suffixes using the domains you list. That covers simple cases like stores.chemist.example, but it isn't a complete way to reason about registrable domains across all public suffixes. We'll come back to that limitation.

How to read the inspection results

The output only helps if you read it with the right expectations. The script reports what it can observe in the URL. It doesn't give a reliable "safe or dangerous" rating.

A match is a domain comparison, not proof of identity

If the hostname is stores.chemist.example, the script reports that it is inside chemist.example. That lines up with a link on a subdomain of a domain you listed. It doesn't prove the pharmacy sent the SMS. Anyone can paste a legitimate domain into an unsolicited message, and a compromised or misused site can still host harmful content.

Also, the "known" list only works as well as your source for it. If you copied the domain from the text itself, the result tells you very little. Use a source you already rely on - like a printed receipt or an app you installed through your usual app store process.

The text before @ can disguise the real hostname

In the second example, the familiar-looking part appears before the at-sign. URL parsers treat that portion as user information. The destination hostname is collect-rx.test, so it doesn't match your listed domains. This is why focusing only on the first recognizable word in a URL is a habit worth breaking.

Similar spelling and IDNs deserve attention

The third example uses chemist-example.test, a different domain that contains the word chemist, and it uses HTTP rather than HTTPS. Those details are worth checking, but they don't prove anything by themselves. The fourth example uses an accented character. Python converts it to an IDNA form, which can make visually deceptive hostnames easier to notice.

The edit-distance warning is a rough heuristic. It counts small character changes, but it doesn't know brand ownership or the full set of ways domains get made to look similar. Think of it as a prompt to compare carefully, not as a detector that catches every lookalike.

No warning does not mean safe

The fifth example uses a short, unfamiliar hostname. The script doesn't have a reason to treat it as a spelling variation of something known, so it won't flag it. It still says the hostname isn't on your list. The sixth example uses an IP address and no explicit scheme. Neither line tells you what's hosted there or what would happen if you opened it.

Parsing a URL answers a small question: what hostname is written in the address, and does it match a simple rule you supplied? It doesn't answer who sent the text, who owns the destination, whether the site has been compromised, or whether the page will redirect elsewhere. Those questions require evidence the script never collects.

The script also doesn't visit the address. That's intentional. Following redirects or fetching page content adds new risks and still doesn't prove the message is legitimate. A site can change what it serves, tailor content to a visitor, or redirect after the initial request. Without loading the page, you're limited to static inspection.

There are technical limitations too. The domain check here uses a suffix comparison rather than the Public Suffix List, which is needed to reason correctly about registrable domains across cases like co.uk. Python's built-in IDNA codec follows older IDNA rules and may represent some unusual names differently from a modern browser. The simple token extractor doesn't cover every valid URL format, and malformed ports or unusual encodings may need extra handling.

For this specific task, "more elaborate" isn't automatically better. If you build a homemade phishing score without covering edge cases, you can end up with false confidence. The useful output here is a plain list of facts you can check against what you already know. If you need robust URL classification for a product or security system, you'll want maintained libraries for parsing and domain data, a defined threat model, and testing against real-world cases. That's a bigger project than inspecting one unexpected text locally.

For an unexpected prescription notice, the safer decision often doesn't depend on analyzing the link at all. If you're expecting medication, open the pharmacy app you already use or call the branch using a number from an existing receipt or another trusted record. Don't use the number or link in the questionable message to "verify" that same message. If you weren't expecting a prescription, you don't need to follow the link to find out.

In the UK, mobile users can report spam texts by forwarding them to 7726, then deleting the message. Reporting helps networks investigate; it still doesn't prove who sent a specific text. In the US, use your carrier's spam-reporting process or the reporting options in your device. The right route depends on where you are and who your provider is.

Conclusion: use a route you already trust

A small Python script can make an SMS link's structure easier to read without requesting the page. It can expose a misleading @, a lookalike hostname, a non-HTTPS scheme, or an address that doesn't match your trusted list. Those are helpful observations - but they don't prove a text is genuine or that a site is safe.

For a prescription reminder, the most dependable check is usually independent of the message: use the pharmacy app you already have or call the branch using a number from a trusted source. Keep URL inspection in its proper role - understanding an address, not permission to tap it.

Frequently Asked Questions

No. Python can parse the URL and reveal details such as its hostname, scheme, and user information. A local script cannot verify who sent the message, establish site ownership, or predict what a page will do. Use the result as one clue, not a safety verdict.
No. HTTPS encrypts the connection to the site named in the URL. It does not prove that the site belongs to a pharmacy or that the text came from that organization. Check the hostname against a source you trust independently.
In a URL such as https://familiar-name.example@other.test/, the text before @ is user information. The hostname after it is other.test. Do not assume the first familiar-looking name is the destination site.
Not on that basis alone. The script’s rules are limited, and an unfamiliar short domain may produce no specific warning. If you need to check a prescription, use the pharmacy’s app or contact the branch through a number you already trust.

Related articles