How to detect if request came from mobile device

11,930

Solution 1

The general answer is no. You get a header / message from a device. All you know about the device is in the header and the device can write what it wants in it. If you are talking about http requests (which is indicated by agent lookup) you can look at a header here:

All you can do "reliable" is to look for the user agent. In my case it is Mozilla Firefox on Linux. But I could fake it if I want.

Host: somesite.org
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:34.0) Gecko/20100101 Firefox/34.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://somesite.org/index.php?page=2
Cookie: rteStatus=rte; 
Cache-Control: max-age=0

Maybe you can get some informations from the referer if it is some chromium-mobile site or you can have a look at Accept and Accept-Enconding, maybe some mobile browsers accept different stuff. But there is no reliable way to determine the device but by its user Agent via header.

An other approach is to look if the request comes from an IP known as 3G or 4G pool. But this would just work if the requests is not coming via WLAN / WIFI. And I am not sure if a list of 3G / 4G IP address pools exists.

Solution 2

You can use UserAgent string for detecting. Below code in C#.

 public bool IsMobileDevice(HttpRequest r){
                    String userAgetnt = r.UserAgent;
                    String deviceName = "Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini";
                    return Regex.IsMatch (r.UserAgent, deviceName);
                }
Share:
11,930
azrahel
Author by

azrahel

Started software engineering in 2011. Still going strong :). Javascript FTW.

Updated on June 20, 2022

Comments

  • azrahel
    azrahel almost 2 years

    On server side is there any way to detect that particular request to API came from mobile device (from mobile app)? I know about user agent sniffing but I dont like this aproach from few enough reasons not to implement it. I also know I could add some flag to request when it comes from my mobile app, but this seems bit dirty as well. Are there actually any 'proper' ways to do it?

    I guess it doesn't change much but my backend is in node.js.

    Greetings, thanks! Tom

  • Rafael
    Rafael over 4 years
    Of course "User-Agent" is not reliable at all. The only option might work is some kind of device-id that is known by google/apple ... if user sends request providing that id we could check ... "hey google is this deviceID valid aside with this user account?"
  • asafadd
    asafadd over 3 years
    The python version for this is: def isMobileDevice(request): result = False devices = ["Android", "webOS", "iPhone", "iPad", "iPod", "BlackBerry", "IEMobile", "Opera Mini"] if any (device in request.environ["HTTP_USER_AGENT"] for device in devices): result = True return result