Networking in C · beginner · ~8 min
Make a TCP connection from a client to a server.
connect(fd, &addr, sizeof addr) initiates the TCP handshake to addr. Blocks until the connection succeeds (returns 0) or fails (returns -1 with errno).
Common errors on connect:
ECONNREFUSED — nothing is listening on the target port.ETIMEDOUT — the remote host didn't answer in time.EADDRNOTAVAIL — you ran out of source ports (rare on labs).After a successful connect, treat fd like any other fd: write() to send, read() to receive.
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
int main(void) {
int fd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in a; memset(&a, 0, sizeof a);
a.sin_family = AF_INET;
a.sin_port = htons(8080);
a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
if (connect(fd, (struct sockaddr *)&a, sizeof a) < 0) { perror("connect"); return 1; }
write(fd, "ping\n", 5);
char buf[64]; ssize_t n = read(fd, buf, sizeof buf - 1);
if (n > 0) { buf[n] = 0; printf("%s", buf); }
close(fd);
return 0;
}
connect() does the TCP handshake. ECONNREFUSED = no listener. After success, read/write like any fd.