10.8.12

C - Socket programming

Two processes can communicate in different mode. Across a network the most common method is using sockets.
What is a socket? A socket in an end point of communication between two system on a network.
Typically is a combination of two elements: a ip address and a port number, which identify the process on the machine.
In this article I will show an example of client/server using sockets in C.

Server code

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>

int main (int argc, char*argv[]) {

int listenfd = 0;
int connectionfd = 0;
struct sockaddr_in server_address;

char* buffer;

/** socket(domain, protocol, 0): create a socket inside the kernel and return a socket descriptor
* AF_INET: domain of ipv4 addresses
* SOCK_STREAM: trasport layer protocol - TCP
*/
listenfd = socket (AF_INET, SOCK_STREAM, 0);

//Details of server address: AF_INET family, listening from any ip on port 9000.
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = htonl (INADDR_ANY);
server_address.sin_port = htons (9000);

//bind(fd, serv_addr, sizeof(serv_addr)): assign the sockaddr to the socket created.
bind(listenfd,(struct sockaddr*)&server_address, sizeof(server_address));

//listen(fd, max_number_of_listening_clients):  the socket starts listening
listen (listenfd, 10);

while (1) {

/** accept(fd, sockaddr, sizeof(sockaddr)) 
* sockaddr is a parameter filled in with the address of the connecting entity.
* If addr is NULL, no information about the remote address of the accepted socket is returned.
NB: run in an infinite loop
*/
connectionfd = accept (listenfd, (struct sockaddr*)NULL, NULL);

buffer = "Hello client!\n";
write(connectionfd, buffer, strlen(buffer));

close (connectionfd);
}
}

Nessun commento:

Posta un commento