File: HostName.hs

package info (click to toggle)
haskell-hostname 1.0-18
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 56 kB
  • sloc: haskell: 34; makefile: 2
file content (48 lines) | stat: -rw-r--r-- 1,429 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
module Network.HostName (
    HostName, getHostName
  ) where

import Foreign.C.Error
import Foreign.C.String
import Foreign.C.Types
import Foreign.Marshal.Array

#ifdef WINDOWS

import Foreign.Marshal.Utils
import Foreign.Ptr
import Foreign.Storable

import System.Win32.Types

foreign import stdcall unsafe "windows.h GetComputerNameExW" getComputerNameEx :: COMPUTER_NAME_FORMAT -> LPTSTR -> LPDWORD -> IO BOOL

type COMPUTER_NAME_FORMAT = CInt

computerNamePhysicalDnsHostname :: COMPUTER_NAME_FORMAT
computerNamePhysicalDnsHostname = 5

getHostName :: IO HostName
getHostName = with 0 $ \p_charcount -> do
    -- On the first run, determine the character count and ignore any error we get
    _ <- getComputerNameEx computerNamePhysicalDnsHostname nullPtr p_charcount
    charcount <- peek p_charcount
    
    -- The second time around, use the correct character count to retrieve the data
    withTString (replicate (fromIntegral charcount) ' ') $ \name -> do
        failIfFalse_ "GetComputerNameExW" $ getComputerNameEx computerNamePhysicalDnsHostname name p_charcount
        peekTString name

#else

foreign import ccall unsafe "gethostname" gethostname :: CString -> CSize -> IO CInt

getHostName :: IO HostName
getHostName = allocaArray0 size $ \cstr -> do
        throwErrnoIfMinus1_ "getHostName" $ gethostname cstr (fromIntegral size)
        peekCString cstr
    where size = 256

#endif

type HostName = String