{-# LANGUAGE CPP #-}

#include "HsNetDef.h"

module Network.Socket.If (
    ifNameToIndex
  , ifIndexToName
  ) where

import Foreign.Marshal.Alloc (allocaBytes)

import Network.Socket.Imports

-- | Returns the index corresponding to the interface name.
--
--   Since 2.7.0.0.
ifNameToIndex :: String -> IO (Maybe Int)
ifNameToIndex :: String -> IO (Maybe Int)
ifNameToIndex String
ifname = do
  CUInt
index <- forall a. String -> (CString -> IO a) -> IO a
withCString String
ifname CString -> IO CUInt
c_if_nametoindex
  -- On failure zero is returned. We'll return Nothing.
  forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ if CUInt
index forall a. Eq a => a -> a -> Bool
== CUInt
0 then forall a. Maybe a
Nothing else forall a. a -> Maybe a
Just forall a b. (a -> b) -> a -> b
$ forall a b. (Integral a, Num b) => a -> b
fromIntegral CUInt
index

-- | Returns the interface name corresponding to the index.
--
--   Since 2.7.0.0.
ifIndexToName :: Int -> IO (Maybe String)
ifIndexToName :: Int -> IO (Maybe String)
ifIndexToName Int
ifn = forall a b. Int -> (Ptr a -> IO b) -> IO b
allocaBytes Int
16 forall a b. (a -> b) -> a -> b
$ \CString
ptr -> do -- 16 == IFNAMSIZ
    CString
r <- CUInt -> CString -> IO CString
c_if_indextoname (forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
ifn) CString
ptr
    if CString
r forall a. Eq a => a -> a -> Bool
== forall a. Ptr a
nullPtr then
        forall (m :: * -> *) a. Monad m => a -> m a
return forall a. Maybe a
Nothing
      else
        forall a. a -> Maybe a
Just forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> CString -> IO String
peekCString CString
ptr

foreign import CALLCONV safe "if_nametoindex"
   c_if_nametoindex :: CString -> IO CUInt

foreign import CALLCONV safe "if_indextoname"
   c_if_indextoname :: CUInt -> CString -> IO CString