Testing if hostname is numeric IPv4

I had to resort this hack when testing a hybrid web/mobile site which uses site hostname based device discrimination. In production mode we can have m.yoursite.com and www.yoursite.com hostnames. However, when running the site locally, on your development computer and in LAN this does not work very well: one cannot spoof hostnames for web browsers in devices like iPhone/iPod/other mobile phone unless you install a DNS server. And installing a DNS server for LAN is something you don’t want to do…

So, I figured out that I can use  hostname spoofing on desktop computers (/etc/hosts file) and I always access the site via numeric IP (IPv4 over ethernet) when testing over WLAN on mobile devices.

  • The site is rendered in web mode when it is being accessed via textual hostname (localhost, yourpcname)
  • The site is rendered in mobile mode when it is being accessed via IPv4 numeric hostname (127.0.0.1, 196.168.200.1)

And,… dadaa,… here is my magical code to test whether hostname is numeric IPv4. I couldn’t find a ready function from Python standard library

import re

ipv4_regex_source = "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"
ipv4_regex = re.compile(ipv4_regex_source)

def is_numeric_ipv4(str):
    """

    http://answers.oreilly.com/topic/318-how-to-match-ipv4-addresses-with-regular-expressions/

    @param str: Hostname as a string.

    @return: True if the given string is numeric IPv4 address
    """
    # ^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$
    return ipv4_regex.match(str)

\"\" Subscribe to RSS feed Follow me on Twitter Follow me on Facebook Follow me Google+

2 thoughts on “Testing if hostname is numeric IPv4

  1. I do this sometimes:

    >>> socket.inet_aton(‘653.999.121.2’)
    Traceback (most recent call last):
    File “”, line 1, in
    socket.error: illegal IP address string passed to inet_aton
    >>>

  2. Could this be what you wanted?

    import socket
    def is_numeric_ipv4(astr): # avoid masking the str type
    try:
    socket.inet_aton(astr)
    except socket.error:
    return False
    else:
    return True

    Hope the code and indentation comes through ok.

Leave a Reply

Your email address will not be published. Required fields are marked *