{
    "mode": "perldoc",
    "parameter": "IO::Socket",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/IO%3A%3ASocket/json",
    "generated": "2026-06-03T03:33:37Z",
    "synopsis": "use strict;\nuse warnings;\nuse IO::Socket qw(AFINET AFUNIX);\n# create a new AFINET socket\nmy $sock = IO::Socket->new(Domain => AFINET);\n# which is the same as\n$sock = IO::Socket::INET->new();\n# create a new AFUNIX socket\n$sock = IO::Socket->new(Domain => AFUNIX);\n# which is the same as\n$sock = IO::Socket::UNIX->new();",
    "sections": {
        "NAME": {
            "content": "IO::Socket - Object interface to socket communications\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "use strict;\nuse warnings;\n\nuse IO::Socket qw(AFINET AFUNIX);\n\n# create a new AFINET socket\nmy $sock = IO::Socket->new(Domain => AFINET);\n# which is the same as\n$sock = IO::Socket::INET->new();\n\n# create a new AFUNIX socket\n$sock = IO::Socket->new(Domain => AFUNIX);\n# which is the same as\n$sock = IO::Socket::UNIX->new();\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "\"IO::Socket\" provides an object-oriented, IO::Handle-based interface to creating and using\nsockets via Socket, which provides a near one-to-one interface to the C socket library.\n\n\"IO::Socket\" is a base class that really only defines methods for those operations which are\ncommon to all types of sockets. Operations which are specific to a particular socket domain have\nmethods defined in subclasses of \"IO::Socket\". See IO::Socket::INET, IO::Socket::UNIX, and\nIO::Socket::IP for examples of such a subclass.\n\n\"IO::Socket\" will export all functions (and constants) defined by Socket.\n",
            "subsections": []
        },
        "CONSTRUCTOR ARGUMENTS": {
            "content": "Given that \"IO::Socket\" doesn't have attributes in the traditional sense, the following\narguments, rather than attributes, can be passed into the constructor.\n\nConstructor arguments should be passed in \"Key => 'Value'\" pairs.\n\nThe only required argument is \"Domain\" in IO::Socket.\n",
            "subsections": [
                {
                    "name": "Blocking",
                    "content": "my $sock = IO::Socket->new(..., Blocking => 1);\n$sock = IO::Socket->new(..., Blocking => 0);\n\nIf defined but false, the socket will be set to non-blocking mode. If not specified it defaults\nto 1 (blocking mode).\n"
                },
                {
                    "name": "Domain",
                    "content": "my $sock = IO::Socket->new(Domain => IO::Socket::AFINET);\n$sock = IO::Socket->new(Domain => IO::Socket::AFUNIX);\n\nThe socket domain will define which subclass of \"IO::Socket\" to use. The two options available\nalong with this distribution are \"AFINET\" and \"AFUNIX\".\n\n\"AFINET\" is for the internet address family of sockets and is handled via IO::Socket::INET.\n\"AFINET\" sockets are bound to an internet address and port.\n\n\"AFUNIX\" is for the unix domain socket and is handled via IO::Socket::UNIX. \"AFUNIX\" sockets\nare bound to the file system as their address name space.\n\nThis argument is required. All other arguments are optional.\n"
                },
                {
                    "name": "Listen",
                    "content": "my $sock = IO::Socket->new(..., Listen => 5);\n\nListen should be an integer value or left unset.\n\nIf provided, this argument will place the socket into listening mode. New connections can then\nbe accepted using the \"accept\" in IO::Socket method. The value given is used as the listen(2)\nqueue size.\n\nIf the \"Listen\" argument is given, but false, the queue size will be set to 5.\n"
                },
                {
                    "name": "Timeout",
                    "content": "my $sock = IO::Socket->new(..., Timeout => 5);\n\nThe timeout value, in seconds, for this socket connection. How exactly this value is utilized is\ndefined in the socket domain subclasses that make use of the value.\n"
                },
                {
                    "name": "Type",
                    "content": "my $sock = IO::Socket->new(..., Type => IO::Socket::SOCKSTREAM);\n\nThe socket type that will be used. These are usually \"SOCKSTREAM\", \"SOCKDGRAM\", or \"SOCKRAW\".\nIf this argument is left undefined an attempt will be made to infer the type from the service\nname.\n\nFor example, you'll usually use \"SOCKSTREAM\" with a \"tcp\" connection and \"SOCKDGRAM\" with a\n\"udp\" connection.\n"
                }
            ]
        },
        "CONSTRUCTORS": {
            "content": "\"IO::Socket\" extends the IO::Handle constructor.\n\nnew\nmy $sock = IO::Socket->new();\n\n# get a new IO::Socket::INET instance\n$sock = IO::Socket->new(Domain => IO::Socket::AFINET);\n# get a new IO::Socket::UNIX instance\n$sock = IO::Socket->new(Domain => IO::Socket::AFUNIX);\n\n# Domain is the only required argument\n$sock = IO::Socket->new(\nDomain => IO::Socket::AFINET, # AFINET, AFUNIX\nType => IO::Socket::SOCKSTREAM, # SOCKSTREAM, SOCKDGRAM, ...\nProto => 'tcp', # 'tcp', 'udp', IPPROTOTCP, IPPROTOUDP\n# and so on...\n);\n\nCreates an \"IO::Socket\", which is a reference to a newly created symbol (see the Symbol\npackage). \"new\" optionally takes arguments, these arguments are defined in \"CONSTRUCTOR\nARGUMENTS\" in IO::Socket.\n\nAny of the \"CONSTRUCTOR ARGUMENTS\" in IO::Socket may be passed to the constructor, but if any\narguments are provided, then one of them must be the \"Domain\" in IO::Socket argument. The\n\"Domain\" in IO::Socket argument can, by default, be either \"AFINET\" or \"AFUNIX\". Other domains\ncan be used if a proper subclass for the domain family is registered. All other arguments will\nbe passed to the \"configuration\" method of the package for that domain.\n\nIf the constructor fails it will return \"undef\" and set the $errstr package variable to contain\nan error message.\n\n$sock = IO::Socket->new(...)\nor die \"Cannot create socket - $IO::Socket::errstr\\n\";\n\nFor legacy reasons the error message is also set into the global $@ variable, and you may still\nfind older code which looks here instead.\n\n$sock = IO::Socket->new(...)\nor die \"Cannot create socket - $@\\n\";\n",
            "subsections": []
        },
        "METHODS": {
            "content": "\"IO::Socket\" inherits all methods from IO::Handle and implements the following new ones.\n\naccept\nmy $clientsock = $sock->accept();\nmy $inetsock = $sock->accept('IO::Socket::INET');\n\nThe accept method will perform the system call \"accept\" on the socket and return a new object.\nThe new object will be created in the same class as the listen socket, unless a specific package\nname is specified. This object can be used to communicate with the client that was trying to\nconnect.\n\nThis differs slightly from the \"accept\" function in perlfunc.\n\nIn a scalar context the new socket is returned, or \"undef\" upon failure. In a list context a\ntwo-element array is returned containing the new socket and the peer address; the list will be\nempty upon failure.\n\natmark\nmy $integer = $sock->atmark();\n# read in some data on a given socket\nmy $data;\n$sock->read($data, 1024) until $sock->atmark;\n\n# or, export the function to use:\nuse IO::Socket 'sockatmark';\n$sock->read($data, 1024) until sockatmark($sock);\n\nTrue if the socket is currently positioned at the urgent data mark, false otherwise. If your\nsystem doesn't yet implement \"sockatmark\" this will throw an exception.\n\nIf your system does not support \"sockatmark\", the \"use\" declaration will fail at compile time.\n\nautoflush\n# by default, autoflush will be turned on when referenced\n$sock->autoflush(); # turns on autoflush\n# turn off autoflush\n$sock->autoflush(0);\n# turn on autoflush\n$sock->autoflush(1);\n\nThis attribute isn't overridden from IO::Handle's implementation. However, since we turn it on\nby default, it's worth mentioning here.\n\nbind\nuse Socket qw(packsockaddrin);\nmy $port = 3000;\nmy $ipaddress = '0.0.0.0';\nmy $packedaddr = packsockaddrin($port, $ipaddress);\n$sock->bind($packedaddr);\n\nBinds a network address to a socket, just as bind(2) does. Returns true if it succeeded, false\notherwise. You should provide a packed address of the appropriate type for the socket.\n\nconnected\nmy $peeraddr = $sock->connected();\nif ($peeraddr) {\nsay \"We're connected to $peeraddr\";\n}\n\nIf the socket is in a connected state, the peer address is returned. If the socket is not in a\nconnected state, \"undef\" is returned.\n\nNote that this method considers a half-open TCP socket to be \"in a connected state\".\nSpecifically, it does not distinguish between the ESTABLISHED and CLOSE-WAIT TCP states; it\nreturns the peer address, rather than \"undef\", in either case. Thus, in general, it cannot be\nused to reliably learn whether the peer has initiated a graceful shutdown because in most cases\n(see below) the local TCP state machine remains in CLOSE-WAIT until the local application calls\n\"shutdown\" in IO::Socket or \"close\". Only at that point does this function return \"undef\".\n\nThe \"in most cases\" hedge is because local TCP state machine behavior may depend on the peer's\nsocket options. In particular, if the peer socket has \"SOLINGER\" enabled with a zero timeout,\nthen the peer's \"close\" will generate a \"RST\" segment. Upon receipt of that segment, the local\nTCP transitions immediately to CLOSED, and in that state, this method *will* return \"undef\".\n\ngetsockopt\nmy $value = $sock->getsockopt(SOLSOCKET, SOREUSEADDR);\nmy $buf = $socket->getsockopt(SOLSOCKET, SORCVBUF);\nsay \"Receive buffer is $buf bytes\";\n\nGet an option associated with the socket. Levels other than \"SOLSOCKET\" may be specified here.\nAs a convenience, this method will unpack a byte buffer of the correct size back into a number.\n\nlisten\n$sock->listen(5);\n\nDoes the same thing that the listen(2) system call does. Returns true if it succeeded, false\notherwise. Listens to a socket with a given queue size.\n\npeername\nmy $sockaddrin = $sock->peername();\n\nReturns the packed \"sockaddr\" address of the other end of the socket connection. It calls\n\"getpeername\".\n\nprotocol\nmy $proto = $sock->protocol();\n\nReturns the number for the protocol being used on the socket, if known. If the protocol is\nunknown, as with an \"AFUNIX\" socket, zero is returned.\n\nrecv\nmy $buffer = \"\";\nmy $length = 1024;\nmy $flags = 0; # default. optional\n$sock->recv($buffer, $length);\n$sock->recv($buffer, $length, $flags);\n\nSimilar in functionality to \"recv\" in perlfunc.\n\nReceives a message on a socket. Attempts to receive $length characters of data into $buffer from\nthe specified socket. $buffer will be grown or shrunk to the length actually read. Takes the\nsame flags as the system call of the same name. Returns the address of the sender if socket's\nprotocol supports this; returns an empty string otherwise. If there's an error, returns \"undef\".\nThis call is actually implemented in terms of the recvfrom(2) system call.\n\nFlags are ORed together values, such as \"MSGBCAST\", \"MSGOOB\", \"MSGTRUNC\". The default value\nfor the flags is 0.\n\nThe cached value of \"peername\" in IO::Socket is updated with the result of \"recv\".\n\nNote: In Perl v5.30 and newer, if the socket has been marked as \":utf8\", \"recv\" will throw an\nexception. The \":encoding(...)\" layer implicitly introduces the \":utf8\" layer. See \"binmode\" in\nperlfunc.\n\nNote: In Perl versions older than v5.30, depending on the status of the socket, either (8-bit)\nbytes or characters are received. By default all sockets operate on bytes, but for example if\nthe socket has been changed using \"binmode\" in perlfunc to operate with the \":encoding(UTF-8)\"\nI/O layer (see the \"open\" in perlfunc pragma), the I/O will operate on UTF8-encoded Unicode\ncharacters, not bytes. Similarly for the \":encoding\" layer: in that case pretty much any\ncharacters can be read.\n\nsend\nmy $message = \"Hello, world!\";\nmy $flags = 0; # defaults to zero\nmy $to = '0.0.0.0'; # optional destination\nmy $sent = $sock->send($message);\n$sent = $sock->send($message, $flags);\n$sent = $sock->send($message, $flags, $to);\n\nSimilar in functionality to \"send\" in perlfunc.\n\nSends a message on a socket. Attempts to send the scalar message to the socket. Takes the same\nflags as the system call of the same name. On unconnected sockets, you must specify a\ndestination to send to, in which case it does a sendto(2) syscall. Returns the number of\ncharacters sent, or \"undef\" on error. The sendmsg(2) syscall is currently unimplemented.\n\nThe \"flags\" option is optional and defaults to 0.\n\nAfter a successful send with $to, further calls to \"send\" on an unconnected socket without $to\nwill send to the same address, and $to will be used as the result of \"peername\" in IO::Socket.\n\nNote: In Perl v5.30 and newer, if the socket has been marked as \":utf8\", \"send\" will throw an\nexception. The \":encoding(...)\" layer implicitly introduces the \":utf8\" layer. See \"binmode\" in\nperlfunc.\n\nNote: In Perl versions older than v5.30, depending on the status of the socket, either (8-bit)\nbytes or characters are sent. By default all sockets operate on bytes, but for example if the\nsocket has been changed using \"binmode\" in perlfunc to operate with the \":encoding(UTF-8)\" I/O\nlayer (see the \"open\" in perlfunc pragma), the I/O will operate on UTF8-encoded Unicode\ncharacters, not bytes. Similarly for the \":encoding\" layer: in that case pretty much any\ncharacters can be sent.\n\nsetsockopt\n$sock->setsockopt(SOLSOCKET, SOREUSEADDR, 1);\n$sock->setsockopt(SOLSOCKET, SORCVBUF, 64*1024);\n\nSet option associated with the socket. Levels other than \"SOLSOCKET\" may be specified here. As\na convenience, this method will convert a number into a packed byte buffer.\n\nshutdown\n$sock->shutdown(SHUTRD); # we stopped reading data\n$sock->shutdown(SHUTWR); # we stopped writing data\n$sock->shutdown(SHUTRDWR); # we stopped using this socket\n\nShuts down a socket connection in the manner indicated by the value passed in, which has the\nsame interpretation as in the syscall of the same name.\n\nThis is useful with sockets when you want to tell the other side you're done writing but not\ndone reading, or vice versa. It's also a more insistent form of \"close\" because it also disables\nthe file descriptor in any forked copies in other processes.\n\nReturns 1 for success; on error, returns \"undef\" if the socket is not a valid filehandle, or\nreturns 0 and sets $! for any other failure.\n\nsockdomain\nmy $domain = $sock->sockdomain();\n\nReturns the number for the socket domain type. For example, for an \"AFINET\" socket the value of\n&AFINET will be returned.\n\nsocket\nmy $sock = IO::Socket->new(); # no values given\n# now let's actually get a socket with the socket method\n# domain, type, and protocol are required\n$sock = $sock->socket(AFINET, SOCKSTREAM, 'tcp');\n\nOpens a socket of the specified kind and returns it. Domain, type, and protocol are specified\nthe same as for the syscall of the same name.\n\nsocketpair\nmy ($r, $w) = $sock->socketpair(AFUNIX, SOCKSTREAM, PFUNSPEC);\n($r, $w) = IO::Socket::UNIX\n->socketpair(AFUNIX, SOCKSTREAM, PFUNSPEC);\n\nWill return a list of two sockets created (read and write), or an empty list on failure.\n\nDiffers slightly from \"socketpair\" in perlfunc in that the argument list is a bit simpler.\n\nsockname\nmy $packedaddr = $sock->sockname();\n\nReturns the packed \"sockaddr\" address of this end of the connection. It's the same as",
            "subsections": [
                {
                    "name": "getsockname",
                    "content": "sockopt\nmy $value = $sock->sockopt(SOREUSEADDR);\n$sock->sockopt(SOREUSEADDR, 1);\n\nUnified method to both set and get options in the \"SOLSOCKET\" level. If called with one\nargument then \"getsockopt\" in IO::Socket is called, otherwise \"setsockopt\" in IO::Socket is\ncalled.\n\nsocktype\nmy $type = $sock->socktype();\n\nReturns the number for the socket type. For example, for a \"SOCKSTREAM\" socket the value of\n&SOCKSTREAM will be returned.\n\ntimeout\nmy $seconds = $sock->timeout();\nmy $oldval = $sock->timeout(5); # set new and return old value\n\nSet or get the timeout value (in seconds) associated with this socket. If called without any\narguments then the current setting is returned. If called with an argument the current setting\nis changed and the previous value returned.\n\nThis method is available to all \"IO::Socket\" implementations but may or may not be used by the\nindividual domain subclasses.\n"
                }
            ]
        },
        "EXAMPLES": {
            "content": "Let's create a TCP server on \"localhost:3333\".\n\nuse strict;\nuse warnings;\nuse feature 'say';\n\nuse IO::Socket qw(AFINET AFUNIX SOCKSTREAM SHUTWR);\n\nmy $server = IO::Socket->new(\nDomain => AFINET,\nType => SOCKSTREAM,\nProto => 'tcp',\nLocalHost => '0.0.0.0',\nLocalPort => 3333,\nReusePort => 1,\nListen => 5,\n) || die \"Can't open socket: $IO::Socket::errstr\";\nsay \"Waiting on 3333\";\n\nwhile (1) {\n# waiting for a new client connection\nmy $client = $server->accept();\n\n# get information about a newly connected client\nmy $clientaddress = $client->peerhost();\nmy $clientport = $client->peerport();\nsay \"Connection from $clientaddress:$clientport\";\n\n# read up to 1024 characters from the connected client\nmy $data = \"\";\n$client->recv($data, 1024);\nsay \"received data: $data\";\n\n# write response data to the connected client\n$data = \"ok\";\n$client->send($data);\n\n# notify client that response has been sent\n$client->shutdown(SHUTWR);\n}\n\n$server->close();\n\nA client for such a server could be\n\nuse strict;\nuse warnings;\nuse feature 'say';\n\nuse IO::Socket qw(AFINET AFUNIX SOCKSTREAM SHUTWR);\n\nmy $client = IO::Socket->new(\nDomain => AFINET,\nType => SOCKSTREAM,\nproto => 'tcp',\nPeerPort => 3333,\nPeerHost => '0.0.0.0',\n) || die \"Can't open socket: $IO::Socket::errstr\";\n\nsay \"Sending Hello World!\";\nmy $size = $client->send(\"Hello World!\");\nsay \"Sent data of length: $size\";\n\n$client->shutdown(SHUTWR);\n\nmy $buffer;\n$client->recv($buffer, 1024);\nsay \"Got back $buffer\";\n\n$client->close();\n",
            "subsections": []
        },
        "LIMITATIONS": {
            "content": "On some systems, for an IO::Socket object created with \"newfromfd\", or created with \"accept\"\nin IO::Socket from such an object, the \"protocol\" in IO::Socket, \"sockdomain\" in IO::Socket and\n\"socktype\" in IO::Socket methods may return \"undef\".\n",
            "subsections": []
        },
        "SEE ALSO": {
            "content": "Socket, IO::Handle, IO::Socket::INET, IO::Socket::UNIX, IO::Socket::IP\n",
            "subsections": []
        },
        "AUTHOR": {
            "content": "Graham Barr. atmark() by Lincoln Stein. Currently maintained by the Perl Porters. Please report\nall bugs to <perlbug@perl.org>.\n",
            "subsections": []
        },
        "COPYRIGHT": {
            "content": "Copyright (c) 1997-8 Graham Barr <gbarr@pobox.com>. All rights reserved. This program is free\nsoftware; you can redistribute it and/or modify it under the same terms as Perl itself.\n\nThe atmark() implementation: Copyright 2001, Lincoln Stein <lstein@cshl.org>. This module is\ndistributed under the same terms as Perl itself. Feel free to use, modify and redistribute it as\nlong as you retain the correct attribution.\n",
            "subsections": []
        }
    },
    "summary": "IO::Socket - Object interface to socket communications",
    "flags": [],
    "examples": [
        "Let's create a TCP server on \"localhost:3333\".",
        "use strict;",
        "use warnings;",
        "use feature 'say';",
        "use IO::Socket qw(AFINET AFUNIX SOCKSTREAM SHUTWR);",
        "my $server = IO::Socket->new(",
        "Domain => AFINET,",
        "Type => SOCKSTREAM,",
        "Proto => 'tcp',",
        "LocalHost => '0.0.0.0',",
        "LocalPort => 3333,",
        "ReusePort => 1,",
        "Listen => 5,",
        ") || die \"Can't open socket: $IO::Socket::errstr\";",
        "say \"Waiting on 3333\";",
        "while (1) {",
        "# waiting for a new client connection",
        "my $client = $server->accept();",
        "# get information about a newly connected client",
        "my $clientaddress = $client->peerhost();",
        "my $clientport = $client->peerport();",
        "say \"Connection from $clientaddress:$clientport\";",
        "# read up to 1024 characters from the connected client",
        "my $data = \"\";",
        "$client->recv($data, 1024);",
        "say \"received data: $data\";",
        "# write response data to the connected client",
        "$data = \"ok\";",
        "$client->send($data);",
        "# notify client that response has been sent",
        "$client->shutdown(SHUTWR);",
        "$server->close();",
        "A client for such a server could be",
        "use strict;",
        "use warnings;",
        "use feature 'say';",
        "use IO::Socket qw(AFINET AFUNIX SOCKSTREAM SHUTWR);",
        "my $client = IO::Socket->new(",
        "Domain => AFINET,",
        "Type => SOCKSTREAM,",
        "proto => 'tcp',",
        "PeerPort => 3333,",
        "PeerHost => '0.0.0.0',",
        ") || die \"Can't open socket: $IO::Socket::errstr\";",
        "say \"Sending Hello World!\";",
        "my $size = $client->send(\"Hello World!\");",
        "say \"Sent data of length: $size\";",
        "$client->shutdown(SHUTWR);",
        "my $buffer;",
        "$client->recv($buffer, 1024);",
        "say \"Got back $buffer\";",
        "$client->close();"
    ],
    "see_also": []
}