我想让用户IPv4
和/或IPv6
在GeoIp2上使用。
如何获得它?
-----编辑--------
就像用户访问我的网站一样,我想知道他们的IP地址是什么,我想用GeoIp2找到它们。
以下示例具有默认的IPv4和IPv6地址:
{-# LANGUAGE OverloadedStrings #-}
import Data.GeoIP2
import Data.IP (IP(..))
main = do
geodb <- openGeoDB "GeoLite2-City.mmdb"
let ip = IPv4 "23.253.242.70"
print $ (findGeoData geodb "en" ip :: Maybe GeoResult)
let ip2 = IPv6 "2001:4800:7817:104:be76:4eff:fe04:f608"
print $ (findGeoData geodb "en" ip2 :: Maybe GeoResult)
希望有所帮助
答案 0 :(得分:2)
这应该有效:
import Network.Wai (remoteHost) -- From the wai package
import Data.IP -- From the iproute package
import Network.Socket.Internal (SockAddr(..)) -- From the network package
sockAddrToIP :: SockAddr -> IP
sockAddrToIP sockAddr = case sockAddr of
SockAddrInet _port hostAddress -> IPv4 $ fromHostAddress hostAddress
SockAddrInet6 _port _flowInfo hostAddress6 _scopeID -> IPv6 $ fromHostAddress6 hostAddress6
-- I don't know how to handle these, they might not apply to the web?
SockAddrUnix _ -> error "Couldn't get IP address"
SockAddrCan _ -> error "Couldn't get IP address"
getHomeR :: Handler Html
getHomeR = do
host <- remoteHost <$> waiRequest
let ip = sockAddrToIP host
traceShowM $ "Remote host is " ++ show host
traceShowM $ "IP is " ++ show ip
-- (Finish implementing the handler here)
当我在本地运行时,我得到:
"Remote host is 127.0.0.1:54575"
"IP is 127.0.0.1"
我实际上对网络或IP地址或其他任何东西都不太了解,但是这些类型排成一行并且代码似乎正常工作。如果有人可以验证可以忽略SockAddrUnix
和SockAddrCan
,那就很好。