Using client-side sockets in connected mode

In C language:

After creating the socket, you will have to use the connect function by passing it 3 parameters:

We will therefore have to declare a variant of the sockaddr structure corresponding to AF_INET. This is the struct sockaddr_in type. We will start by zeroing the content of this structure via the bzero function of string.h, then we will assign, to the first field, named here sin_family, the AF_INET value.

struct sockaddr_in	addr;

bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
	

You must then fill in the structure, the field sin_addr with the IPv4 address of the server to contact and the field sin_port with the number of its TCP port.

Notes:

inet_aton("127.0.0.1", &addr.sin_addr);
addr.sin_port = htons(80);
	

Having thus specified the address 127.0.0.1 and the port 80, all that remains is to call the connect function so that the client tries to establish the connection with the local web server.

connect(fd, (struct sockaddr *) &addr, sizeof(addr));
	

Example:

#include <stdio.h>
#include <stdlib.h>

#include <sys/types.h>
#include <netdb.h>
#include <sys/socket.h>

#include <string.h>		// for the function bzero
#include <arpa/inet.h>	// for the function inet_addr

void customer_dialog(int fd) {

}

int main()
{
	int 	fd;
	struct sockaddr_in	addr;
	int		err;

	fd = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (fd<0) {
		printf("Socket creation error!\n");
		exit(1);
	}

	bzero(&addr, sizeof(addr));
	addr.sin_family = AF_INET;
	err = inet_aton("127.0.0.1", &addr.sin_addr);
	if (err == 0) {
		printf("Invalid IPv4 address!\n");
		exit(1);
	}
	addr.sin_port = htons(8080);
	err = connect(fd, (struct sockaddr *) &addr, sizeof(addr));
	if (err != 0) {
		printf("Server connection error!\n");
		exit(1);
	}

	printf("Connection established with the server!\n");
	customer_dialog(fd);
	return 0;
}
	

PHP and Python:

In languages like PHP or Python, there are libraries interfacing with system functions.

PHP

The example code written in C becomes in PHP:

function customer_dialog($socket) {

}

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket == false) die("Socket creation error!\n");
$err=socket_connect($socket, '127.0.0.1', 8080);
if ($err == false) die("Server connection error!\n");
echo "Connection established with the server!\n";
customer_dialog($socket);
	

Python

The example code written in C becomes in Python:

def customer_dialog(sock) :
	...

try :
	sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	sock.connect(('127.0.0.1',8080))
	customer_dialog(sock)
except socket.error :
	print("Client launch error!")
	exit()
print("Connection established with the server!")