Freigeben über


Getting the Name of your Windows Phone 8 device

You can name your phone to whatever you like, but how can an app display that name? There isn't an obvious API for this, but I accidentally discovered an un-obvious API. The quick version is that you can ask getaddrinfo for the canonical network name. Too quick? OK, here is some C++/CX code to show exactly:

 Platform::String ^ DeviceName::PhoneName::get()
{
    WSADATA wsadata;
    ADDRINFOA *result = nullptr;
    int error;
    wchar_t wszName[256] = L"Unknown";
    ADDRINFOA hints = {};
 
    hints.ai_flags = AI_CANONNAME;
 
    error = WSAStartup(MAKEWORD(2,2), &wsadata);
    if (error==0)
    {
        error = ::getaddrinfo("", "0", &hints, &result);
        if (error==0)
        {
            char *name = result->ai_canonname;
            if (name!=nullptr)
            {
                MultiByteToWideChar(CP_ACP, 0, name, strlen(name), wszName, 256);
            }
        }
    }
 
    ::freeaddrinfo(result);
 
    return ref new Platform::String(wszName);
}

If you haven't used C++/CX on the phone you might need a little more info on how to hook this up, so here is the C++/CX Super-QuickStart guide by me:

Load your C# project into VS2012. Right click on the Solution then Add / New Project / Visual C++ / Windows Phone / Windows Phone Runtime Component and call it NetHelper.

In pch.h add:

 #include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>

Replace NetHelper.h with this simple ref class containing a single static property:

 #pragma once
 
namespace NetHelper
{
    public ref class DeviceName sealed
    {
    public:
        static property Platform::String ^ PhoneName
        {
            Platform::String ^ get();
        }
    };
}

Replace NetHelper.cpp with the code at the start of the article, prefixed with this:

 #include "pch.h"
#include "NetHelper.h"
 
using namespace NetHelper;
using namespace Platform;
 
#pragma comment(lib, "ws2_32.lib")

Build the NetHelper project.

Right click on your C# project's References tree / Add Reference / Solution / add a checkmark next to NetHelper / OK

In C# you can now using it with

 var name = NetHelper.DeviceName.PhoneName;

That's it!

Comments

  • Anonymous
    September 21, 2014
    Why not simply:    using Windows.Networking.Proximity;    var name = PeerFinder.DisplayName; Also, how to do it for Windows Phone 7? I get this error: "Unable to add the specified project reference. The reference must be a Windows Phone project that targets the current or earlier version of the Windows Phone OS." See this thread: stackoverflow.com/.../how-to-call-wsastartup-in-c-sharp-on-windows-phone-7