# %socket() function

The %socket() function creates a socket
in the specified *addr.family* and of the specified *type*. A protocol can be specified or assigned by the system.
If the protocol is left unspecified (with a value of 0), the system
selects an appropriate protocol in the specified *addr.family*.

## Syntax

```
n = %socket(addr.family, type, protocol)
```

## Parameter(s)

| addr.family | Specifies the addressing scheme used later to decode addresses. Valid values are defined in the include file: dm,bp,unix.h socket.h. Commonly used values are: |
| --- | --- |
| af$inet | IPv4 |
| af$inet6 | IPv6 |
| type | Specifies the semantics of communication. Valid values are defined in the include: dm,bp,unix.h socket.h. Commonly used values are: |
| sock$stream | Socket streams |
| sock$dgram | Datagram |
| protocol | Should be left to 0, to let the system assign the protocol. |

## Description

To compile successfully, the
statement cfunction socket.builtin must be
included in the source code.

Upon successful completion, a valid
file descriptor is returned. If the call fails, a value of -1 is returned
and the system(0) function returns the value of errno.

The socket is closed by a %close call or automatically when the FlashBASIC program terminates.

Note: A call to open a network socket in a D3 process running on
a pib or phantom will consume a user license if one is not already
consumed. If no licenses are available, - 7 is returned.

## Example(s)

```
cfunction socket.builtin
include dm,bp,includes sysid.inc
include dm,bp,unix.h socket.h
fd=%socket(af$inet, sock$stream, 0)
if fd<0 then
 crt ’Socket creation failed. Error ’:system(0)
```

## See also

- [%accept() function](https://d3codex.com/pickbasic-flashbasic/percent-accept-function/)
- [%bind() function](https://d3codex.com/pickbasic-flashbasic/percent-bind-function/)
- [%close() function](https://d3codex.com/pickbasic-flashbasic/percent-close-function/)
- [%connect() function](https://d3codex.com/pickbasic-flashbasic/percent-connect-function/)
- [%gethostid() function](https://d3codex.com/pickbasic-flashbasic/percent-gethostid-function/)
- [%listen() function](https://d3codex.com/pickbasic-flashbasic/percent-listen-function/)
- [cfunction statement](https://d3codex.com/pickbasic-flashbasic/cfunction-statement/)
- [tape-socket command](https://d3codex.com/tcl/tape-socket-command/)

---
Source: https://d3codex.com/pickbasic-flashbasic/percent-socket-function/ - part of the D3Codex reference.
