Linux Kernel Architecture

(Jacob Rumans) #1

Chapter 12: Networks


analogs for little endian values. They are all defined in<types.h>. Note that both little and big endian
types resolve to the same data types finally (namely,u32and so on, as introduced in Chapter 1), but
an explicit specification of the byte order allows for checking correctness of code with automated type
checking tools.

12.3.2 Using Sockets


It is assumed that you are familiar with the userland side of network programming. However, to briefly
illustrate how sockets represent an interface to the network layer of the kernel, I discuss two very brief
sample programs, one that acts as a client for echo requests, the other as a server. A text string is sent
from the client to the server and is returned unchanged. The TCP/IP protocol is used.

Echo Client


The source code for the echo client is as follows^5 :

#include<stdio.h>
#include<netinet/in.h>
#include<sys/types.h>
#include<string.h>

int main() {
/* Host and port number of the echo server */
char* echo_host = "192.168.1.20";
int echo_port = 7;
int sockfd;
struct sockaddr_in *server=
(struct sockaddr_in*)malloc(sizeof(struct sockaddr_in));

/* Set address of server to be connected */
server->sin_family = AF_INET;
server->sin_port = htons(echo_port); // Note network byte order!
server->sin_addr.s_addr = inet_addr(echo_host);

/* Create a socket (Internet address family, stream socket and
default protocol) */
sockfd = socket(AF_INET, SOCK_STREAM, 0);

/* Connect to server */
printf("Connecting to %s \n", echo_host);
printf("Numeric: %u\n", server->sin_addr);
connect(sockfd, (struct sockaddr*)server, sizeof(*server));

/* Send message */
char* msg = "Hello World";
printf("\nSend: ā€™%sā€™\n", msg);
write(sockfd, msg, strlen(msg));

/* ... and receive result */
char* buf = (char*)malloc(1000); // Receive buffer for max. 1000 chars
int bytes = read(sockfd, (void*)buf, 1000);

(^5) To simplify matters, all error checks that would be performed in a genuine, robust implementation are omitted.

Free download pdf