{
    "mode": "perldoc",
    "parameter": "IO::Socket::IP",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/IO%3A%3ASocket%3A%3AIP/json",
    "generated": "2026-06-15T14:43:27Z",
    "synopsis": "use IO::Socket::IP;\nmy $sock = IO::Socket::IP->new(\nPeerHost => \"www.google.com\",\nPeerPort => \"http\",\nType     => SOCKSTREAM,\n) or die \"Cannot construct socket - $@\";\nmy $familyname = ( $sock->sockdomain == PFINET6 ) ? \"IPv6\" :\n( $sock->sockdomain == PFINET  ) ? \"IPv4\" :\n\"unknown\";\nprintf \"Connected to google via %s\\n\", $familyname;",
    "sections": {
        "NAME": {
            "content": "\"IO::Socket::IP\" - Family-neutral IP socket supporting both IPv4 and IPv6\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "use IO::Socket::IP;\n\nmy $sock = IO::Socket::IP->new(\nPeerHost => \"www.google.com\",\nPeerPort => \"http\",\nType     => SOCKSTREAM,\n) or die \"Cannot construct socket - $@\";\n\nmy $familyname = ( $sock->sockdomain == PFINET6 ) ? \"IPv6\" :\n( $sock->sockdomain == PFINET  ) ? \"IPv4\" :\n\"unknown\";\n\nprintf \"Connected to google via %s\\n\", $familyname;\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "This module provides a protocol-independent way to use IPv4 and IPv6 sockets, intended as a\nreplacement for IO::Socket::INET. Most constructor arguments and methods are provided in a\nbackward-compatible way. For a list of known differences, see the \"IO::Socket::INET\"\nINCOMPATIBILITES section below.\n\nIt uses the getaddrinfo(3) function to convert hostnames and service names or port numbers into\nsets of possible addresses to connect to or listen on. This allows it to work for IPv6 where the\nsystem supports it, while still falling back to IPv4-only on systems which don't.\n\nREPLACING \"IO::Socket\" DEFAULT BEHAVIOUR\nBy placing \"-register\" in the import list to \"IO::Socket::IP\", it will register itself with\nIO::Socket as the class that handles \"PFINET\". It will also ask to handle \"PFINET6\" as well,\nprovided that constant is available.\n\nChanging \"IO::Socket\"'s default behaviour means that calling the \"IO::Socket\" constructor with\neither \"PFINET\" or \"PFINET6\" as the \"Domain\" parameter will yield an \"IO::Socket::IP\" object.\n\nuse IO::Socket::IP -register;\n\nmy $sock = IO::Socket->new(\nDomain    => PFINET6,\nLocalHost => \"::1\",\nListen    => 1,\n) or die \"Cannot create socket - $@\\n\";\n\nprint \"Created a socket of type \" . ref($sock) . \"\\n\";\n\nNote that \"-register\" is a global setting that applies to the entire program; it cannot be\napplied only for certain callers, removed, or limited by lexical scope.\n",
            "subsections": []
        },
        "CONSTRUCTORS": {
            "content": "new\n$sock = IO::Socket::IP->new( %args )\n\nCreates a new \"IO::Socket::IP\" object, containing a newly created socket handle according to the\nnamed arguments passed. The recognised arguments are:\n\nPeerHost => STRING\nPeerService => STRING\nHostname and service name for the peer to \"connect()\" to. The service name may be given\nas a port number, as a decimal string.\n\nPeerAddr => STRING\nPeerPort => STRING\nFor symmetry with the accessor methods and compatibility with \"IO::Socket::INET\", these\nare accepted as synonyms for \"PeerHost\" and \"PeerService\" respectively.\n\nPeerAddrInfo => ARRAY\nAlternate form of specifying the peer to \"connect()\" to. This should be an array of the\nform returned by \"Socket::getaddrinfo\".\n\nThis parameter takes precedence over the \"Peer*\", \"Family\", \"Type\" and \"Proto\"\narguments.\n\nLocalHost => STRING\nLocalService => STRING\nHostname and service name for the local address to \"bind()\" to.\n\nLocalAddr => STRING\nLocalPort => STRING\nFor symmetry with the accessor methods and compatibility with \"IO::Socket::INET\", these\nare accepted as synonyms for \"LocalHost\" and \"LocalService\" respectively.\n\nLocalAddrInfo => ARRAY\nAlternate form of specifying the local address to \"bind()\" to. This should be an array\nof the form returned by \"Socket::getaddrinfo\".\n\nThis parameter takes precedence over the \"Local*\", \"Family\", \"Type\" and \"Proto\"\narguments.\n\nFamily => INT\nThe address family to pass to \"getaddrinfo\" (e.g. \"AFINET\", \"AFINET6\"). Normally this\nwill be left undefined, and \"getaddrinfo\" will search using any address family supported\nby the system.\n\nType => INT\nThe socket type to pass to \"getaddrinfo\" (e.g. \"SOCKSTREAM\", \"SOCKDGRAM\"). Normally\ndefined by the caller; if left undefined \"getaddrinfo\" may attempt to infer the type\nfrom the service name.\n\nProto => STRING or INT\nThe IP protocol to use for the socket (e.g. 'tcp', \"IPPROTOTCP\", 'udp',\"IPPROTOUDP\").\nNormally this will be left undefined, and either \"getaddrinfo\" or the kernel will choose\nan appropriate value. May be given either in string name or numeric form.\n\nGetAddrInfoFlags => INT\nMore flags to pass to the \"getaddrinfo()\" function. If not supplied, a default of\n\"AIADDRCONFIG\" will be used.\n\nThese flags will be combined with \"AIPASSIVE\" if the \"Listen\" argument is given. For\nmore information see the documentation about \"getaddrinfo()\" in the Socket module.\n\nListen => INT\nIf defined, puts the socket into listening mode where new connections can be accepted\nusing the \"accept\" method. The value given is used as the listen(2) queue size.\n\nReuseAddr => BOOL\nIf true, set the \"SOREUSEADDR\" sockopt\n\nReusePort => BOOL\nIf true, set the \"SOREUSEPORT\" sockopt (not all OSes implement this sockopt)\n\nBroadcast => BOOL\nIf true, set the \"SOBROADCAST\" sockopt\n\nSockopts => ARRAY\nAn optional array of other socket options to apply after the three listed above. The\nvalue is an ARRAY containing 2- or 3-element ARRAYrefs. Each inner array relates to a\nsingle option, giving the level and option name, and an optional value. If the value\nelement is missing, it will be given the value of a platform-sized integer 1 constant\n(i.e. suitable to enable most of the common boolean options).\n\nFor example, both options given below are equivalent to setting \"ReuseAddr\".\n\nSockopts => [\n[ SOLSOCKET, SOREUSEADDR ],\n[ SOLSOCKET, SOREUSEADDR, pack( \"i\", 1 ) ],\n]\n\nV6Only => BOOL\nIf defined, set the \"IPV6V6ONLY\" sockopt when creating \"PFINET6\" sockets to the given\nvalue. If true, a listening-mode socket will only listen on the \"AFINET6\" addresses; if\nfalse it will also accept connections from \"AFINET\" addresses.\n\nIf not defined, the socket option will not be changed, and default value set by the\noperating system will apply. For repeatable behaviour across platforms it is recommended\nthis value always be defined for listening-mode sockets.\n\nNote that not all platforms support disabling this option. Some, at least OpenBSD and\nMirBSD, will fail with \"EINVAL\" if you attempt to disable it. To determine whether it is\npossible to disable, you may use the class method\n\nif( IO::Socket::IP->CANDISABLEV6ONLY ) {\n...\n}\nelse {\n...\n}\n\nIf your platform does not support disabling this option but you still want to listen for\nboth \"AFINET\" and \"AFINET6\" connections you will have to create two listening sockets,\none bound to each protocol.\n\nMultiHomed\nThis \"IO::Socket::INET\"-style argument is ignored, except if it is defined but false.\nSee the \"IO::Socket::INET\" INCOMPATIBILITES section below.\n\nHowever, the behaviour it enables is always performed by \"IO::Socket::IP\".\n\nBlocking => BOOL\nIf defined but false, the socket will be set to non-blocking mode. Otherwise it will\ndefault to blocking mode. See the NON-BLOCKING section below for more detail.\n\nTimeout => NUM\nIf defined, gives a maximum time in seconds to block per \"connect()\" call when in\nblocking mode. If missing, no timeout is applied other than that provided by the\nunderlying operating system. When in non-blocking mode this parameter is ignored.\n\nNote that if the hostname resolves to multiple address candidates, the same timeout will\napply to each connection attempt individually, rather than to the operation as a whole.\nFurther note that the timeout does not apply to the initial hostname resolve operation,\nif connecting by hostname.\n\nThis behviour is copied inspired by \"IO::Socket::INET\"; for more fine grained control\nover connection timeouts, consider performing a nonblocking connect directly.\n\nIf neither \"Type\" nor \"Proto\" hints are provided, a default of \"SOCKSTREAM\" and \"IPPROTOTCP\"\nrespectively will be set, to maintain compatibility with \"IO::Socket::INET\". Other named\narguments that are not recognised are ignored.\n\nIf neither \"Family\" nor any hosts or addresses are passed, nor any *AddrInfo, then the\nconstructor has no information on which to decide a socket family to create. In this case, it\nperforms a \"getaddinfo\" call with the \"AIADDRCONFIG\" flag, no host name, and a service name of\n\"0\", and uses the family of the first returned result.\n\nIf the constructor fails, it will set $@ to an appropriate error message; this may be from $! or\nit may be some other string; not every failure necessarily has an associated \"errno\" value.\n\nnew (one arg)\n$sock = IO::Socket::IP->new( $peeraddr )\n\nAs a special case, if the constructor is passed a single argument (as opposed to an even-sized\nlist of key/value pairs), it is taken to be the value of the \"PeerAddr\" parameter. This is\nparsed in the same way, according to the behaviour given in the \"PeerHost\" AND \"LocalHost\"\nPARSING section below.\n",
            "subsections": []
        },
        "METHODS": {
            "content": "As well as the following methods, this class inherits all the methods in IO::Socket and\nIO::Handle.\n\nsockhostservice\n( $host, $service ) = $sock->sockhostservice( $numeric )\n\nReturns the hostname and service name of the local address (that is, the socket address given by\nthe \"sockname\" method).\n\nIf $numeric is true, these will be given in numeric form rather than being resolved into names.\n\nThe following four convenience wrappers may be used to obtain one of the two values returned\nhere. If both host and service names are required, this method is preferable to the following\nwrappers, because it will call getnameinfo(3) only once.\n\nsockhost\n$addr = $sock->sockhost\n\nReturn the numeric form of the local address as a textual representation\n\nsockport\n$port = $sock->sockport\n\nReturn the numeric form of the local port number\n\nsockhostname\n$host = $sock->sockhostname\n\nReturn the resolved name of the local address\n\nsockservice\n$service = $sock->sockservice\n\nReturn the resolved name of the local port number\n\nsockaddr\n$addr = $sock->sockaddr\n\nReturn the local address as a binary octet string\n\npeerhostservice\n( $host, $service ) = $sock->peerhostservice( $numeric )\n\nReturns the hostname and service name of the peer address (that is, the socket address given by\nthe \"peername\" method), similar to the \"sockhostservice\" method.\n\nThe following four convenience wrappers may be used to obtain one of the two values returned\nhere. If both host and service names are required, this method is preferable to the following\nwrappers, because it will call getnameinfo(3) only once.\n\npeerhost\n$addr = $sock->peerhost\n\nReturn the numeric form of the peer address as a textual representation\n\npeerport\n$port = $sock->peerport\n\nReturn the numeric form of the peer port number\n\npeerhostname\n$host = $sock->peerhostname\n\nReturn the resolved name of the peer address\n\npeerservice\n$service = $sock->peerservice\n\nReturn the resolved name of the peer port number\n\npeeraddr\n$addr = $peer->peeraddr\n\nReturn the peer address as a binary octet string\n\nasinet\n$inet = $sock->asinet\n\nReturns a new IO::Socket::INET instance wrapping the same filehandle. This may be useful in\ncases where it is required, for backward-compatibility, to have a real object of\n\"IO::Socket::INET\" type instead of \"IO::Socket::IP\". The new object will wrap the same\nunderlying socket filehandle as the original, so care should be taken not to continue to use\nboth objects concurrently. Ideally the original $sock should be discarded after this method is\ncalled.\n\nThis method checks that the socket domain is \"PFINET\" and will throw an exception if it isn't.\n",
            "subsections": []
        },
        "NON-BLOCKING": {
            "content": "If the constructor is passed a defined but false value for the \"Blocking\" argument then the\nsocket is put into non-blocking mode. When in non-blocking mode, the socket will not be set up\nby the time the constructor returns, because the underlying connect(2) syscall would otherwise\nhave to block.\n\nThe non-blocking behaviour is an extension of the \"IO::Socket::INET\" API, unique to\n\"IO::Socket::IP\", because the former does not support multi-homed non-blocking connect.\n\nWhen using non-blocking mode, the caller must repeatedly check for writeability on the\nfilehandle (for instance using \"select\" or \"IO::Poll\"). Each time the filehandle is ready to\nwrite, the \"connect\" method must be called, with no arguments. Note that some operating systems,\nmost notably \"MSWin32\" do not report a \"connect()\" failure using write-ready; so you must also\n\"select()\" for exceptional status.\n\nWhile \"connect\" returns false, the value of $! indicates whether it should be tried again (by\nbeing set to the value \"EINPROGRESS\", or \"EWOULDBLOCK\" on MSWin32), or whether a permanent error\nhas occurred (e.g. \"ECONNREFUSED\").\n\nOnce the socket has been connected to the peer, \"connect\" will return true and the socket will\nnow be ready to use.\n\nNote that calls to the platform's underlying getaddrinfo(3) function may block. If\n\"IO::Socket::IP\" has to perform this lookup, the constructor will block even when in\nnon-blocking mode.\n\nTo avoid this blocking behaviour, the caller should pass in the result of such a lookup using\nthe \"PeerAddrInfo\" or \"LocalAddrInfo\" arguments. This can be achieved by using Net::LibAsyncNS,\nor the getaddrinfo(3) function can be called in a child process.\n\nuse IO::Socket::IP;\nuse Errno qw( EINPROGRESS EWOULDBLOCK );\n\nmy @peeraddrinfo = ... # Caller must obtain the getaddinfo result here\n\nmy $socket = IO::Socket::IP->new(\nPeerAddrInfo => \\@peeraddrinfo,\nBlocking     => 0,\n) or die \"Cannot construct socket - $@\";\n\nwhile( !$socket->connect and ( $! == EINPROGRESS || $! == EWOULDBLOCK ) ) {\nmy $wvec = '';\nvec( $wvec, fileno $socket, 1 ) = 1;\nmy $evec = '';\nvec( $evec, fileno $socket, 1 ) = 1;\n\nselect( undef, $wvec, $evec, undef ) or die \"Cannot select - $!\";\n}\n\ndie \"Cannot connect - $!\" if $!;\n\n...\n\nThe example above uses \"select()\", but any similar mechanism should work analogously.\n\"IO::Socket::IP\" takes care when creating new socket filehandles to preserve the actual file\ndescriptor number, so such techniques as \"poll\" or \"epoll\" should be transparent to its\nreallocation of a different socket underneath, perhaps in order to switch protocol family\nbetween \"PFINET\" and \"PFINET6\".\n\nFor another example using \"IO::Poll\" and \"Net::LibAsyncNS\", see the\nexamples/nonblockinglibasyncns.pl file in the module distribution.\n\n\"PeerHost\" AND \"LocalHost\" PARSING\nTo support the \"IO::Socket::INET\" API, the host and port information may be passed in a single\nstring rather than as two separate arguments.\n\nIf either \"LocalHost\" or \"PeerHost\" (or their \"...Addr\" synonyms) have any of the following\nspecial forms then special parsing is applied.\n\nThe value of the \"...Host\" argument will be split to give both the hostname and port (or service\nname):\n\nhostname.example.org:http    # Host name\n192.0.2.1:80                 # IPv4 address\n[2001:db8::1]:80             # IPv6 address\n\nIn each case, the port or service name (e.g. 80) is passed as the \"LocalService\" or\n\"PeerService\" argument.\n\nEither of \"LocalService\" or \"PeerService\" (or their \"...Port\" synonyms) can be either a service\nname, a decimal number, or a string containing both a service name and number, in a form such as\n\nhttp(80)\n\nIn this case, the name (\"http\") will be tried first, but if the resolver does not understand it\nthen the port number (80) will be used instead.\n\nIf the \"...Host\" argument is in this special form and the corresponding \"...Service\" or\n\"...Port\" argument is also defined, the one parsed from the \"...Host\" argument will take\nprecedence and the other will be ignored.\n\nsplitaddr\n( $host, $port ) = IO::Socket::IP->splitaddr( $addr )\n\nUtility method that provides the parsing functionality described above. Returns a 2-element\nlist, containing either the split hostname and port description if it could be parsed, or the\ngiven address and \"undef\" if it was not recognised.\n\nIO::Socket::IP->splitaddr( \"hostname:http\" )\n# ( \"hostname\",  \"http\" )\n\nIO::Socket::IP->splitaddr( \"192.0.2.1:80\" )\n# ( \"192.0.2.1\", \"80\"   )\n\nIO::Socket::IP->splitaddr( \"[2001:db8::1]:80\" )\n# ( \"2001:db8::1\", \"80\" )\n\nIO::Socket::IP->splitaddr( \"something.else\" )\n# ( \"something.else\", undef )\n\njoinaddr\n$addr = IO::Socket::IP->joinaddr( $host, $port )\n\nUtility method that performs the reverse of \"splitaddr\", returning a string formed by joining\nthe specified host address and port number. The host address will be wrapped in \"[]\" brackets if\nrequired (because it is a raw IPv6 numeric address).\n\nThis can be especially useful when combined with the \"sockhostservice\" or \"peerhostservice\"\nmethods.\n\nsay \"Connected to \", IO::Socket::IP->joinaddr( $sock->peerhostservice );\n\n\"IO::Socket::INET\" INCOMPATIBILITES\n*   The behaviour enabled by \"MultiHomed\" is in fact implemented by \"IO::Socket::IP\" as it is\nrequired to correctly support searching for a useable address from the results of the\ngetaddrinfo(3) call. The constructor will ignore the value of this argument, except if it is\ndefined but false. An exception is thrown in this case, because that would request it\ndisable the getaddrinfo(3) search behaviour in the first place.\n\n*   \"IO::Socket::IP\" implements both the \"Blocking\" and \"Timeout\" parameters, but it implements\nthe interaction of both in a different way.\n\nIn \"::INET\", supplying a timeout overrides the non-blocking behaviour, meaning that the\n\"connect()\" operation will still block despite that the caller asked for a non-blocking\nsocket. This is not explicitly specified in its documentation, nor does this author believe\nthat is a useful behaviour - it appears to come from a quirk of implementation.\n\nIn \"::IP\" therefore, the \"Blocking\" parameter takes precedence - if a non-blocking socket is\nrequested, no operation will block. The \"Timeout\" parameter here simply defines the maximum\ntime that a blocking \"connect()\" call will wait, if it blocks at all.\n\nIn order to specifically obtain the \"blocking connect then non-blocking send and receive\"\nbehaviour of specifying this combination of options to \"::INET\" when using \"::IP\", perform\nfirst a blocking connect, then afterwards turn the socket into nonblocking mode.\n\nmy $sock = IO::Socket::IP->new(\nPeerHost => $peer,\nTimeout => 20,\n) or die \"Cannot connect - $@\";\n\n$sock->blocking( 0 );\n\nThis code will behave identically under both \"IO::Socket::INET\" and \"IO::Socket::IP\".\n",
            "subsections": []
        },
        "TODO": {
            "content": "*   Investigate whether \"POSIX::dup2\" upsets BSD's \"kqueue\" watchers, and if so, consider what\npossible workarounds might be applied.\n",
            "subsections": []
        },
        "AUTHOR": {
            "content": "Paul Evans <leonerd@leonerd.org.uk>\n",
            "subsections": []
        }
    },
    "summary": "\"IO::Socket::IP\" - Family-neutral IP socket supporting both IPv4 and IPv6",
    "flags": [],
    "examples": [],
    "see_also": []
}