# %connect() function

The %connect() function requests a connection
between two sockets.

## Syntax

```
code = %connect(fd, addr.family, host, port)
```

## Parameter(s)

| fd | File descriptor of the local socket returned by a previous call to the FlashBASIC C function %socket(). |
| --- | --- |
| addr.family | Specifies the addressing scheme used by the protocol. This field must match the address family used when creating the socket. Valid values are defined in the include file: dm,bp,unix.h socket.h. |
| host | Destination host name. The string must be known to the local network manager. Internally, this calls getaddrinfo to resolve the remote host. |
| port | Port number on the distant host. Legal value for this field depends on the protocol. On TCP/IP, for example, valid port numbers are from 1024 to 32767. |

## Description

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

Upon successful completion, a value
of 0 is returned in code. In case of error, a value of -1 is returned
and the system(0) function is set to the value
of errno.

The connection is closed when
the socket is closed.

## Example(s)

```
cfunction socket.builtin
include dm,bp,includes sysid.inc
include dm,bp,unix.h socket.h
* Create a socket
fd=%socket(af$inet,sock$stream,0)
* Connect to the distant host
if %connect(fd,af$inet,"prod",1024)<0 then
 crt ’Connect failed’; stop
end
* Write data to it
msg="CONNECTED"
%send(fd,msg,len(msg))
* Terminate connection
%close(fd)
```

## See also

- [%close() function](https://d3codex.com/pickbasic-flashbasic/percent-close-function/)
- [%socket() function](https://d3codex.com/pickbasic-flashbasic/percent-socket-function/)
- [cfunction statement](https://d3codex.com/pickbasic-flashbasic/cfunction-statement/)

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