{
    "mode": "man",
    "parameter": "socket",
    "section": "3p",
    "url": "https://www.chedong.com/phpMan.php/man/socket/3p/json",
    "generated": "2026-06-13T21:53:51Z",
    "synopsis": "\"Socket\" a low-level module used by, among other things, the IO::Socket family of modules.\nThe following examples demonstrate some low-level uses but a practical program would likely\nuse the higher-level API provided by \"IO::Socket\" or similar instead.\nuse Socket qw(PFINET SOCKSTREAM packsockaddrin inetaton);\nsocket(my $socket, PFINET, SOCKSTREAM, 0)\nor die \"socket: $!\";\nmy $port = getservbyname \"echo\", \"tcp\";\nconnect($socket, packsockaddrin($port, inetaton(\"localhost\")))\nor die \"connect: $!\";\nprint $socket \"Hello, world!\\n\";\nprint <$socket>;\nSee also the \"EXAMPLES\" section.",
    "sections": {
        "NAME": {
            "content": "\"Socket\" - networking constants and support functions\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "\"Socket\" a low-level module used by, among other things, the IO::Socket family of modules.\nThe following examples demonstrate some low-level uses but a practical program would likely\nuse the higher-level API provided by \"IO::Socket\" or similar instead.\n\nuse Socket qw(PFINET SOCKSTREAM packsockaddrin inetaton);\n\nsocket(my $socket, PFINET, SOCKSTREAM, 0)\nor die \"socket: $!\";\n\nmy $port = getservbyname \"echo\", \"tcp\";\nconnect($socket, packsockaddrin($port, inetaton(\"localhost\")))\nor die \"connect: $!\";\n\nprint $socket \"Hello, world!\\n\";\nprint <$socket>;\n\nSee also the \"EXAMPLES\" section.\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "This module provides a variety of constants, structure manipulators and other functions\nrelated to socket-based networking. The values and functions provided are useful when used in\nconjunction with Perl core functions such as socket(), setsockopt() and bind(). It also\nprovides several other support functions, mostly for dealing with conversions of network\naddresses between human-readable and native binary forms, and for hostname resolver\noperations.\n\nSome constants and functions are exported by default by this module; but for backward-\ncompatibility any recently-added symbols are not exported by default and must be requested\nexplicitly. When an import list is provided to the \"use Socket\" line, the default exports are\nnot automatically imported. It is therefore best practice to always to explicitly list all\nthe symbols required.\n\nAlso, some common socket \"newline\" constants are provided: the constants \"CR\", \"LF\", and\n\"CRLF\", as well as $CR, $LF, and $CRLF, which map to \"\\015\", \"\\012\", and \"\\015\\012\". If you\ndo not want to use the literal characters in your programs, then use the constants provided\nhere. They are not exported by default, but can be imported individually, and with the\n\":crlf\" export tag:\n\nuse Socket qw(:DEFAULT :crlf);\n\n$sock->print(\"GET / HTTP/1.0$CRLF\");\n\nThe entire getaddrinfo() subsystem can be exported using the tag \":addrinfo\"; this exports\nthe getaddrinfo() and getnameinfo() functions, and all the \"AI*\", \"NI*\", \"NIx*\" and\n\"EAI*\" constants.\n",
            "subsections": []
        },
        "CONSTANTS": {
            "content": "In each of the following groups, there may be many more constants provided than just the ones\ngiven as examples in the section heading. If the heading ends \"...\" then this means there are\nlikely more; the exact constants provided will depend on the OS and headers found at compile-\ntime.\n\nPFINET, PFINET6, PFUNIX, ...\nProtocol family constants to use as the first argument to socket() or the value of the\n\"SODOMAIN\" or \"SOFAMILY\" socket option.\n\nAFINET, AFINET6, AFUNIX, ...\nAddress family constants used by the socket address structures, to pass to such functions as\ninetpton() or getaddrinfo(), or are returned by such functions as sockaddrfamily().\n\nSOCKSTREAM, SOCKDGRAM, SOCKRAW, ...\nSocket type constants to use as the second argument to socket(), or the value of the\n\"SOTYPE\" socket option.\n\nSOCKNONBLOCK. SOCKCLOEXEC\nLinux-specific shortcuts to specify the \"ONONBLOCK\" and \"FDCLOEXEC\" flags during a\nsocket(2) call.\n\nsocket( my $sockh, PFINET, SOCKDGRAM|SOCKNONBLOCK, 0 )\n\nSOLSOCKET\nSocket option level constant for setsockopt() and getsockopt().\n\nSOACCEPTCONN, SOBROADCAST, SOERROR, ...\nSocket option name constants for setsockopt() and getsockopt() at the \"SOLSOCKET\" level.\n\nIPOPTIONS, IPTOS, IPTTL, ...\nSocket option name constants for IPv4 socket options at the \"IPPROTOIP\" level.\n\nIPPMTUDISCWANT, IPPMTUDISCDONT, ...\nSocket option value constants for \"IPMTUDISCOVER\" socket option.\n\nIPTOSLOWDELAY, IPTOSTHROUGHPUT, IPTOSRELIABILITY, ...\nSocket option value constants for \"IPTOS\" socket option.\n\nMSGBCAST, MSGOOB, MSGTRUNC, ...\nMessage flag constants for send() and recv().\n\nSHUTRD, SHUTRDWR, SHUTWR\nDirection constants for shutdown().\n\nINADDRANY, INADDRBROADCAST, INADDRLOOPBACK, INADDRNONE\nConstants giving the special \"AFINET\" addresses for wildcard, broadcast, local loopback, and\ninvalid addresses.\n\nNormally equivalent to inetaton('0.0.0.0'), inetaton('255.255.255.255'),\ninetaton('localhost') and inetaton('255.255.255.255') respectively.\n\nIPPROTOIP, IPPROTOIPV6, IPPROTOTCP, ...\nIP protocol constants to use as the third argument to socket(), the level argument to\ngetsockopt() or setsockopt(), or the value of the \"SOPROTOCOL\" socket option.\n\nTCPCORK, TCPKEEPALIVE, TCPNODELAY, ...\nSocket option name constants for TCP socket options at the \"IPPROTOTCP\" level.\n\nIN6ADDRANY, IN6ADDRLOOPBACK\nConstants giving the special \"AFINET6\" addresses for wildcard and local loopback.\n\nNormally equivalent to inetpton(AFINET6, \"::\") and inetpton(AFINET6, \"::1\") respectively.\n\nIPV6ADDMEMBERSHIP, IPV6MTU, IPV6V6ONLY, ...\nSocket option name constants for IPv6 socket options at the \"IPPROTOIPV6\" level.\n",
            "subsections": []
        },
        "STRUCTURE MANIPULATORS": {
            "content": "The following functions convert between lists of Perl values and packed binary strings\nrepresenting structures.\n\n$family = sockaddrfamily $sockaddr\nTakes a packed socket address (as returned by packsockaddrin(), packsockaddrun() or the\nperl builtin functions getsockname() and getpeername()). Returns the address family tag. This\nwill be one of the \"AF*\" constants, such as \"AFINET\" for a \"sockaddrin\" addresses or\n\"AFUNIX\" for a \"sockaddrun\". It can be used to figure out what unpack to use for a sockaddr\nof unknown type.\n\n$sockaddr = packsockaddrin $port, $ipaddress\nTakes two arguments, a port number and an opaque string (as returned by inetaton(), or a\nv-string). Returns the \"sockaddrin\" structure with those arguments packed in and \"AFINET\"\nfilled in. For Internet domain sockets, this structure is normally what you need for the\narguments in bind(), connect(), and send().\n\nAn undefined $port argument is taken as zero; an undefined $ipaddress is considered a fatal\nerror.\n\n($port, $ipaddress) = unpacksockaddrin $sockaddr\nTakes a \"sockaddrin\" structure (as returned by packsockaddrin(), getpeername() or recv()).\nReturns a list of two elements: the port and an opaque string representing the IP address\n(you can use inetntoa() to convert the address to the four-dotted numeric format). Will\ncroak if the structure does not represent an \"AFINET\" address.\n\nIn scalar context will return just the IP address.\n\n$sockaddr = sockaddrin $port, $ipaddress\n($port, $ipaddress) = sockaddrin $sockaddr\nA wrapper of packsockaddrin() or unpacksockaddrin(). In list context, unpacks its\nargument and returns a list consisting of the port and IP address.  In scalar context, packs\nits port and IP address arguments as a \"sockaddrin\" and returns it.\n\nProvided largely for legacy compatibility; it is better to use packsockaddrin() or\nunpacksockaddrin() explicitly.\n\n$sockaddr = packsockaddrin6 $port, $ip6address, [$scopeid, [$flowinfo]]\nTakes two to four arguments, a port number, an opaque string (as returned by inetpton()),\noptionally a scope ID number, and optionally a flow label number. Returns the \"sockaddrin6\"\nstructure with those arguments packed in and \"AFINET6\" filled in. IPv6 equivalent of\npacksockaddrin().\n\nAn undefined $port argument is taken as zero; an undefined $ip6address is considered a fatal\nerror.\n\n($port, $ip6address, $scopeid, $flowinfo) = unpacksockaddrin6 $sockaddr\nTakes a \"sockaddrin6\" structure. Returns a list of four elements: the port number, an opaque\nstring representing the IPv6 address, the scope ID, and the flow label. (You can use\ninetntop() to convert the address to the usual string format). Will croak if the structure\ndoes not represent an \"AFINET6\" address.\n\nIn scalar context will return just the IP address.\n\n$sockaddr = sockaddrin6 $port, $ip6address, [$scopeid, [$flowinfo]]\n($port, $ip6address, $scopeid, $flowinfo) = sockaddrin6 $sockaddr\nA wrapper of packsockaddrin6() or unpacksockaddrin6(). In list context, unpacks its\nargument according to unpacksockaddrin6(). In scalar context, packs its arguments according\nto packsockaddrin6().\n\nProvided largely for legacy compatibility; it is better to use packsockaddrin6() or\nunpacksockaddrin6() explicitly.\n\n$sockaddr = packsockaddrun $path\nTakes one argument, a pathname. Returns the \"sockaddrun\" structure with that path packed in\nwith \"AFUNIX\" filled in. For \"PFUNIX\" sockets, this structure is normally what you need for\nthe arguments in bind(), connect(), and send().\n\n($path) = unpacksockaddrun $sockaddr\nTakes a \"sockaddrun\" structure (as returned by packsockaddrun(), getpeername() or recv()).\nReturns a list of one element: the pathname. Will croak if the structure does not represent\nan \"AFUNIX\" address.\n\n$sockaddr = sockaddrun $path\n($path) = sockaddrun $sockaddr\nA wrapper of packsockaddrun() or unpacksockaddrun(). In a list context, unpacks its\nargument and returns a list consisting of the pathname. In a scalar context, packs its\npathname as a \"sockaddrun\" and returns it.\n\nProvided largely for legacy compatibility; it is better to use packsockaddrun() or\nunpacksockaddrun() explicitly.\n\nThese are only supported if your system has <sys/un.h>.\n\n$ipmreq = packipmreq $multiaddr, $interface\nTakes an IPv4 multicast address and optionally an interface address (or \"INADDRANY\").\nReturns the \"ipmreq\" structure with those arguments packed in. Suitable for use with the\n\"IPADDMEMBERSHIP\" and \"IPDROPMEMBERSHIP\" sockopts.\n\n($multiaddr, $interface) = unpackipmreq $ipmreq\nTakes an \"ipmreq\" structure. Returns a list of two elements; the IPv4 multicast address and\ninterface address.\n\n$ipmreqsource = packipmreqsource $multiaddr, $source, $interface\nTakes an IPv4 multicast address, source address, and optionally an interface address (or\n\"INADDRANY\"). Returns the \"ipmreqsource\" structure with those arguments packed in.\nSuitable for use with the \"IPADDSOURCEMEMBERSHIP\" and \"IPDROPSOURCEMEMBERSHIP\"\nsockopts.\n\n($multiaddr, $source, $interface) = unpackipmreqsource $ipmreq\nTakes an \"ipmreqsource\" structure. Returns a list of three elements; the IPv4 multicast\naddress, source address and interface address.\n\n$ipv6mreq = packipv6mreq $multiaddr6, $ifindex\nTakes an IPv6 multicast address and an interface number. Returns the \"ipv6mreq\" structure\nwith those arguments packed in. Suitable for use with the \"IPV6ADDMEMBERSHIP\" and\n\"IPV6DROPMEMBERSHIP\" sockopts.\n\n($multiaddr6, $ifindex) = unpackipv6mreq $ipv6mreq\nTakes an \"ipv6mreq\" structure. Returns a list of two elements; the IPv6 address and an\ninterface number.\n",
            "subsections": []
        },
        "FUNCTIONS": {
            "content": "$ipaddress = inetaton $string\nTakes a string giving the name of a host, or a textual representation of an IP address and\ntranslates that to an packed binary address structure suitable to pass to packsockaddrin().\nIf passed a hostname that cannot be resolved, returns \"undef\". For multi-homed hosts (hosts\nwith more than one address), the first address found is returned.\n\nFor portability do not assume that the result of inetaton() is 32 bits wide, in other words,\nthat it would contain only the IPv4 address in network order.\n\nThis IPv4-only function is provided largely for legacy reasons. Newly-written code should use\ngetaddrinfo() or inetpton() instead for IPv6 support.\n\n$string = inetntoa $ipaddress\nTakes a packed binary address structure such as returned by unpacksockaddrin() (or a\nv-string representing the four octets of the IPv4 address in network order) and translates it\ninto a string of the form \"d.d.d.d\" where the \"d\"s are numbers less than 256 (the normal\nhuman-readable four dotted number notation for Internet addresses).\n\nThis IPv4-only function is provided largely for legacy reasons. Newly-written code should use\ngetnameinfo() or inetntop() instead for IPv6 support.\n\n$address = inetpton $family, $string\nTakes an address family (such as \"AFINET\" or \"AFINET6\") and a string containing a textual\nrepresentation of an address in that family and translates that to an packed binary address\nstructure.\n\nSee also getaddrinfo() for a more powerful and flexible function to look up socket addresses\ngiven hostnames or textual addresses.\n\n$string = inetntop $family, $address\nTakes an address family and a packed binary address structure and translates it into a human-\nreadable textual representation of the address; typically in \"d.d.d.d\" form for \"AFINET\" or\n\"hhhh:hhhh::hhhh\" form for \"AFINET6\".\n\nSee also getnameinfo() for a more powerful and flexible function to turn socket addresses\ninto human-readable textual representations.\n",
            "subsections": [
                {
                    "name": "($err, @result) = getaddrinfo $host, $service, [$hints]",
                    "content": "Given both a hostname and service name, this function attempts to resolve the host name into\na list of network addresses, and the service name into a protocol and port number, and then\nreturns a list of address structures suitable to connect() to it.\n\nGiven just a host name, this function attempts to resolve it to a list of network addresses,\nand then returns a list of address structures giving these addresses.\n\nGiven just a service name, this function attempts to resolve it to a protocol and port\nnumber, and then returns a list of address structures that represent it suitable to bind()\nto. This use should be combined with the \"AIPASSIVE\" flag; see below.\n\nGiven neither name, it generates an error.\n\nIf present, $hints should be a reference to a hash, where the following keys are recognised:\n\nflags => INT\nA bitfield containing \"AI*\" constants; see below.\n\nfamily => INT\nRestrict to only generating addresses in this address family\n\nsocktype => INT\nRestrict to only generating addresses of this socket type\n\nprotocol => INT\nRestrict to only generating addresses for this protocol\n\nThe return value will be a list; the first value being an error indication, followed by a\nlist of address structures (if no error occurred).\n\nThe error value will be a dualvar; comparable to the \"EAI*\" error constants, or printable as\na human-readable error message string. If no error occurred it will be zero numerically and\nan empty string.\n\nEach value in the results list will be a hash reference containing the following fields:\n\nfamily => INT\nThe address family (e.g. \"AFINET\")\n\nsocktype => INT\nThe socket type (e.g. \"SOCKSTREAM\")\n\nprotocol => INT\nThe protocol (e.g. \"IPPROTOTCP\")\n\naddr => STRING\nThe address in a packed string (such as would be returned by packsockaddrin())\n\ncanonname => STRING\nThe canonical name for the host if the \"AICANONNAME\" flag was provided, or \"undef\"\notherwise. This field will only be present on the first returned address.\n\nThe following flag constants are recognised in the $hints hash. Other flag constants may\nexist as provided by the OS.\n\nAIPASSIVE\nIndicates that this resolution is for a local bind() for a passive (i.e.  listening)\nsocket, rather than an active (i.e. connecting) socket.\n\nAICANONNAME\nIndicates that the caller wishes the canonical hostname (\"canonname\") field of the result\nto be filled in.\n\nAINUMERICHOST\nIndicates that the caller will pass a numeric address, rather than a hostname, and that\ngetaddrinfo() must not perform a resolve operation on this name. This flag will prevent a\npossibly-slow network lookup operation, and instead return an error if a hostname is\npassed.\n"
                },
                {
                    "name": "($err, $hostname, $servicename) = getnameinfo $sockaddr, [$flags, [$xflags]]",
                    "content": "Given a packed socket address (such as from getsockname(), getpeername(), or returned by\ngetaddrinfo() in a \"addr\" field), returns the hostname and symbolic service name it\nrepresents. $flags may be a bitmask of \"NI*\" constants, or defaults to 0 if unspecified.\n\nThe return value will be a list; the first value being an error condition, followed by the\nhostname and service name.\n\nThe error value will be a dualvar; comparable to the \"EAI*\" error constants, or printable as\na human-readable error message string. The host and service names will be plain strings.\n\nThe following flag constants are recognised as $flags. Other flag constants may exist as\nprovided by the OS.\n\nNINUMERICHOST\nRequests that a human-readable string representation of the numeric address be returned\ndirectly, rather than performing a name resolve operation that may convert it into a\nhostname. This will also avoid potentially-blocking network IO.\n\nNINUMERICSERV\nRequests that the port number be returned directly as a number representation rather than\nperforming a name resolve operation that may convert it into a service name.\n\nNINAMEREQD\nIf a name resolve operation fails to provide a name, then this flag will cause\ngetnameinfo() to indicate an error, rather than returning the numeric representation as a\nhuman-readable string.\n\nNIDGRAM\nIndicates that the socket address relates to a \"SOCKDGRAM\" socket, for the services\nwhose name differs between TCP and UDP protocols.\n\nThe following constants may be supplied as $xflags.\n\nNIxNOHOST\nIndicates that the caller is not interested in the hostname of the result, so it does not\nhave to be converted. \"undef\" will be returned as the hostname.\n\nNIxNOSERV\nIndicates that the caller is not interested in the service name of the result, so it does\nnot have to be converted. \"undef\" will be returned as the service name.\n"
                },
                {
                    "name": "getaddrinfo() / getnameinfo() ERROR CONSTANTS",
                    "content": "The following constants may be returned by getaddrinfo() or getnameinfo().  Others may be\nprovided by the OS.\n\nEAIAGAIN\nA temporary failure occurred during name resolution. The operation may be successful if\nit is retried later.\n\nEAIBADFLAGS\nThe value of the \"flags\" hint to getaddrinfo(), or the $flags parameter to getnameinfo()\ncontains unrecognised flags.\n\nEAIFAMILY\nThe \"family\" hint to getaddrinfo(), or the family of the socket address passed to\ngetnameinfo() is not supported.\n\nEAINODATA\nThe host name supplied to getaddrinfo() did not provide any usable address data.\n\nEAINONAME\nThe host name supplied to getaddrinfo() does not exist, or the address supplied to\ngetnameinfo() is not associated with a host name and the \"NINAMEREQD\" flag was supplied.\n\nEAISERVICE\nThe service name supplied to getaddrinfo() is not available for the socket type given in\nthe $hints.\n"
                }
            ]
        },
        "EXAMPLES": {
            "content": "",
            "subsections": [
                {
                    "name": "Lookup for connect()",
                    "content": "The getaddrinfo() function converts a hostname and a service name into a list of structures,\neach containing a potential way to connect() to the named service on the named host.\n\nuse IO::Socket;\nuse Socket qw(SOCKSTREAM getaddrinfo);\n\nmy %hints = (socktype => SOCKSTREAM);\nmy ($err, @res) = getaddrinfo(\"localhost\", \"echo\", \\%hints);\ndie \"Cannot getaddrinfo - $err\" if $err;\n\nmy $sock;\n\nforeach my $ai (@res) {\nmy $candidate = IO::Socket->new();\n\n$candidate->socket($ai->{family}, $ai->{socktype}, $ai->{protocol})\nor next;\n\n$candidate->connect($ai->{addr})\nor next;\n\n$sock = $candidate;\nlast;\n}\n\ndie \"Cannot connect to localhost:echo\" unless $sock;\n\n$sock->print(\"Hello, world!\\n\");\nprint <$sock>;\n\nBecause a list of potential candidates is returned, the \"while\" loop tries each in turn until\nit finds one that succeeds both the socket() and connect() calls.\n\nThis function performs the work of the legacy functions gethostbyname(), getservbyname(),\ninetaton() and packsockaddrin().\n\nIn practice this logic is better performed by IO::Socket::IP.\n"
                },
                {
                    "name": "Making a human-readable string out of an address",
                    "content": "The getnameinfo() function converts a socket address, such as returned by getsockname() or\ngetpeername(), into a pair of human-readable strings representing the address and service\nname.\n\nuse IO::Socket::IP;\nuse Socket qw(getnameinfo);\n\nmy $server = IO::Socket::IP->new(LocalPort => 12345, Listen => 1) or\ndie \"Cannot listen - $@\";\n\nmy $socket = $server->accept or die \"accept: $!\";\n\nmy ($err, $hostname, $servicename) = getnameinfo($socket->peername);\ndie \"Cannot getnameinfo - $err\" if $err;\n\nprint \"The peer is connected from $hostname\\n\";\n\nSince in this example only the hostname was used, the redundant conversion of the port number\ninto a service name may be omitted by passing the \"NIxNOSERV\" flag.\n\nuse Socket qw(getnameinfo NIxNOSERV);\n\nmy ($err, $hostname) = getnameinfo($socket->peername, 0, NIxNOSERV);\n\nThis function performs the work of the legacy functions unpacksockaddrin(), inetntoa(),\ngethostbyaddr() and getservbyport().\n\nIn practice this logic is better performed by IO::Socket::IP.\n"
                },
                {
                    "name": "Resolving hostnames into IP addresses",
                    "content": "To turn a hostname into a human-readable plain IP address use getaddrinfo() to turn the\nhostname into a list of socket structures, then getnameinfo() on each one to make it a\nreadable IP address again.\n\nuse Socket qw(:addrinfo SOCKRAW);\n\nmy ($err, @res) = getaddrinfo($hostname, \"\", {socktype => SOCKRAW});\ndie \"Cannot getaddrinfo - $err\" if $err;\n\nwhile( my $ai = shift @res ) {\nmy ($err, $ipaddr) = getnameinfo($ai->{addr}, NINUMERICHOST, NIxNOSERV);\ndie \"Cannot getnameinfo - $err\" if $err;\n\nprint \"$ipaddr\\n\";\n}\n\nThe \"socktype\" hint to getaddrinfo() filters the results to only include one socket type and\nprotocol. Without this most OSes return three combinations, for \"SOCKSTREAM\", \"SOCKDGRAM\"\nand \"SOCKRAW\", resulting in triplicate output of addresses. The \"NINUMERICHOST\" flag to\ngetnameinfo() causes it to return a string-formatted plain IP address, rather than reverse\nresolving it back into a hostname.\n\nThis combination performs the work of the legacy functions gethostbyname() and inetntoa().\n"
                },
                {
                    "name": "Accessing socket options",
                    "content": "The many \"SO*\" and other constants provide the socket option names for getsockopt() and\nsetsockopt().\n\nuse IO::Socket::INET;\nuse Socket qw(SOLSOCKET SORCVBUF IPPROTOIP IPTTL);\n\nmy $socket = IO::Socket::INET->new(LocalPort => 0, Proto => 'udp')\nor die \"Cannot create socket: $@\";\n\n$socket->setsockopt(SOLSOCKET, SORCVBUF, 64*1024) or\ndie \"setsockopt: $!\";\n\nprint \"Receive buffer is \", $socket->getsockopt(SOLSOCKET, SORCVBUF),\n\" bytes\\n\";\n\nprint \"IP TTL is \", $socket->getsockopt(IPPROTOIP, IPTTL), \"\\n\";\n\nAs a convenience, IO::Socket's setsockopt() method will convert a number into a packed byte\nbuffer, and getsockopt() will unpack a byte buffer of the correct size back into a number.\n"
                }
            ]
        },
        "AUTHOR": {
            "content": "This module was originally maintained in Perl core by the Perl 5 Porters.\n\nIt was extracted to dual-life on CPAN at version 1.95 by Paul Evans <leonerd@leonerd.org.uk>\n\n\n\nperl v5.34.0                                 2025-07-25                                Socket(3perl)",
            "subsections": []
        }
    },
    "summary": "\"Socket\" - networking constants and support functions",
    "flags": [],
    "examples": [
        "The getaddrinfo() function converts a hostname and a service name into a list of structures,",
        "each containing a potential way to connect() to the named service on the named host.",
        "use IO::Socket;",
        "use Socket qw(SOCKSTREAM getaddrinfo);",
        "my %hints = (socktype => SOCKSTREAM);",
        "my ($err, @res) = getaddrinfo(\"localhost\", \"echo\", \\%hints);",
        "die \"Cannot getaddrinfo - $err\" if $err;",
        "my $sock;",
        "foreach my $ai (@res) {",
        "my $candidate = IO::Socket->new();",
        "$candidate->socket($ai->{family}, $ai->{socktype}, $ai->{protocol})",
        "or next;",
        "$candidate->connect($ai->{addr})",
        "or next;",
        "$sock = $candidate;",
        "last;",
        "die \"Cannot connect to localhost:echo\" unless $sock;",
        "$sock->print(\"Hello, world!\\n\");",
        "print <$sock>;",
        "Because a list of potential candidates is returned, the \"while\" loop tries each in turn until",
        "it finds one that succeeds both the socket() and connect() calls.",
        "This function performs the work of the legacy functions gethostbyname(), getservbyname(),",
        "inetaton() and packsockaddrin().",
        "In practice this logic is better performed by IO::Socket::IP.",
        "The getnameinfo() function converts a socket address, such as returned by getsockname() or",
        "getpeername(), into a pair of human-readable strings representing the address and service",
        "name.",
        "use IO::Socket::IP;",
        "use Socket qw(getnameinfo);",
        "my $server = IO::Socket::IP->new(LocalPort => 12345, Listen => 1) or",
        "die \"Cannot listen - $@\";",
        "my $socket = $server->accept or die \"accept: $!\";",
        "my ($err, $hostname, $servicename) = getnameinfo($socket->peername);",
        "die \"Cannot getnameinfo - $err\" if $err;",
        "print \"The peer is connected from $hostname\\n\";",
        "Since in this example only the hostname was used, the redundant conversion of the port number",
        "into a service name may be omitted by passing the \"NIxNOSERV\" flag.",
        "use Socket qw(getnameinfo NIxNOSERV);",
        "my ($err, $hostname) = getnameinfo($socket->peername, 0, NIxNOSERV);",
        "This function performs the work of the legacy functions unpacksockaddrin(), inetntoa(),",
        "gethostbyaddr() and getservbyport().",
        "In practice this logic is better performed by IO::Socket::IP.",
        "To turn a hostname into a human-readable plain IP address use getaddrinfo() to turn the",
        "hostname into a list of socket structures, then getnameinfo() on each one to make it a",
        "readable IP address again.",
        "use Socket qw(:addrinfo SOCKRAW);",
        "my ($err, @res) = getaddrinfo($hostname, \"\", {socktype => SOCKRAW});",
        "die \"Cannot getaddrinfo - $err\" if $err;",
        "while( my $ai = shift @res ) {",
        "my ($err, $ipaddr) = getnameinfo($ai->{addr}, NINUMERICHOST, NIxNOSERV);",
        "die \"Cannot getnameinfo - $err\" if $err;",
        "print \"$ipaddr\\n\";",
        "The \"socktype\" hint to getaddrinfo() filters the results to only include one socket type and",
        "protocol. Without this most OSes return three combinations, for \"SOCKSTREAM\", \"SOCKDGRAM\"",
        "and \"SOCKRAW\", resulting in triplicate output of addresses. The \"NINUMERICHOST\" flag to",
        "getnameinfo() causes it to return a string-formatted plain IP address, rather than reverse",
        "resolving it back into a hostname.",
        "This combination performs the work of the legacy functions gethostbyname() and inetntoa().",
        "The many \"SO*\" and other constants provide the socket option names for getsockopt() and",
        "setsockopt().",
        "use IO::Socket::INET;",
        "use Socket qw(SOLSOCKET SORCVBUF IPPROTOIP IPTTL);",
        "my $socket = IO::Socket::INET->new(LocalPort => 0, Proto => 'udp')",
        "or die \"Cannot create socket: $@\";",
        "$socket->setsockopt(SOLSOCKET, SORCVBUF, 64*1024) or",
        "die \"setsockopt: $!\";",
        "print \"Receive buffer is \", $socket->getsockopt(SOLSOCKET, SORCVBUF),",
        "\" bytes\\n\";",
        "print \"IP TTL is \", $socket->getsockopt(IPPROTOIP, IPTTL), \"\\n\";",
        "As a convenience, IO::Socket's setsockopt() method will convert a number into a packed byte",
        "buffer, and getsockopt() will unpack a byte buffer of the correct size back into a number."
    ],
    "see_also": []
}