Raspberry pi Part 23

29
www.techvilla.org.in TECHVILLA www.techvilla.org. in

Transcript of Raspberry pi Part 23

Page 1: Raspberry pi Part 23

www.techvilla.org.in

TECHVILLA

www.techvilla.org.in

Page 2: Raspberry pi Part 23

www.techvilla.org.in

Linux networking

Socket programming concepts.

Writing socket program code

Page 3: Raspberry pi Part 23

www.techvilla.org.in

Socket ProgrammingTable of Contents1. Network Application Programming Interfa

ce: Sockets and Internet Sockets

2. Network Programming Tips3. Client-Server Architecture4. Example: Client Programming5. Example: Server Programming6. Network Programmer’s Mistakes

CEN

45

00

C

3

Page 4: Raspberry pi Part 23

www.techvilla.org.in

Layers of the IP Protocol Suite

CEN

45

00

C

4

Link Layer

Transport Layer

Network Layer

Application Layer

Link Layer

Transport Layer

Network Layer

Application Layer

Ethernet

e.g. ftp

e.g. TCP, UDP

e.g. IP

Page 5: Raspberry pi Part 23

www.techvilla.org.in

Protocol Suite Location

Internet Protocol LayerC

EN

45

00

C

5

Link Layer

Transport Layer (TCP, UDP)

Network Layer (IP)

Application Layer

Network Card &Device Driver

(e.g. Ethernet card)

Operating System(e.g. Unix)

Applications(e.g. browser, game, ftp)

Application ProgrammingInterface (API)

(e.g. network API)

Interface to the Network Card

Location

Page 6: Raspberry pi Part 23

www.techvilla.org.in

Network API

Operating system provides Application Programming Interface (API) for network application

API is defined by a set of function types, data structures, and constants

Desirable characteristics of the network interface Simple to use Flexible

independent from any application

allows program to use all functionality of the network

Standardized allows programmer to learn once, write anywhere

Application Programming Interface for networks is called socket

CEN

45

00

C

6

Page 7: Raspberry pi Part 23

www.techvilla.org.in

SocketsSockets provide mechanisms to communicate between computers across a network

There are different kind of socketsDARPA Internet addresses (Internet Sockets)Unix interprocess communication (Unix Sockets)CCITT X.25 addressesand many others

Berkeley sockets is the most popular Internet Socket runs on Linux, FreeBSD, OS X, Windows

fed by the popularity of TCP/IP

CEN

45

00

C

7

Page 8: Raspberry pi Part 23

www.techvilla.org.in

Internet SocketsSupport stream and datagram packets (e.g. TCP, UDP, IP)

Is Similar to UNIX file I/O API (provides a file descriptor)

Based on C, single thread model does not require multiple threads

CEN

45

00

C

8

Page 9: Raspberry pi Part 23

www.techvilla.org.in

Types of Internet SocketsDifferent types of sockets implement different communication types (stream vs. datagram)Type of socket: stream socket connection-oriented two way communication reliable (error free), in order delivery can use the Transmission Control Protocol (TCP) e.g. telnet, ssh, http

Type of socket: datagram socket connectionless, does not maintain an open

connection, each packet is independent can use the User Datagram Protocol (UDP)

CEN

45

00

C

9

Page 10: Raspberry pi Part 23

www.techvilla.org.in

Network Programming Tips

Byte Ordering

Naming

Addressing

CEN

45

00

C

10

Page 11: Raspberry pi Part 23

www.techvilla.org.in

Byte Ordering of IntegersDifferent CPU architectures have different byte ordering

CEN

45

00

C

11

D3

high-order byte low-order byte

memoryaddress A

memoryaddress A +1

Stored at little-endian computer

Stored at big-endian computer

low-order byte high-order byte

F2Integer representation (2 byte)

Page 12: Raspberry pi Part 23

www.techvilla.org.in

Byte Ordering ProblemQuestion: What would happen if two computers with different integer byte ordering communicate?

CEN

45

00

C

12

Message in Memory ofof big-endian Computer

Message is sent across Network 48 45 4C 4C 6F 01

00

Message is: [Hello,1]

Message is: [Hello,256]

Pro

cess

ing

48 45 4C 4C 6F 01 00

Message in Memory oflittle-endian Computer P

roce

ssin

g

Answer: Nothing if they do not exchange integers! But: If they exchange integers, they would get the

wrong order of bytes, therefore, the wrong value! Example:

Page 13: Raspberry pi Part 23

www.techvilla.org.in

Byte Ordering SolutionThere are two solutions if computers with different byte ordering system want to communicate

They must know the kind of architecture of the sending computer(bad solution, it has not been implemented)

Introduction of a network byte order. The functions are:

uint16_t htons(uint16_t host16bitvalue)

uint32_t htonl(uint32_t host32bitvalue)

uint16_t ntohs(uint16_t net16bitvalue)

uint32_t ntohs(uint32_t net32bitvalue)

Note: use for all integers (short and long), which are sent across the networkIncluding port numbers and IP addresses

CEN

45

00

C

13

Page 14: Raspberry pi Part 23

www.techvilla.org.in

Network Programming Tips

Byte Ordering

Naming

Addressing

CEN

45

00

C

14

Page 15: Raspberry pi Part 23

www.techvilla.org.in

Naming and AddressingHost name identifies a single host (see Domain Name System

slides)variable length string (e.g. www.berkeley.edu) is mapped to one or more IP addresses

IP Addresswritten as dotted octets (e.g. 10.0.0.1)32 bits. Not a number! But often needs to be

converted to a 32-bit to use.

Port number identifies a process on a host16 bit number

CEN

45

00

C

15

Page 16: Raspberry pi Part 23

www.techvilla.org.in

Client-Server Architecture

Client requests service from server

Server responds with sending service or error message to client

CEN

45

00

C

16

Client Server

request

response

Page 17: Raspberry pi Part 23

www.techvilla.org.in

Simple Client-Server Example

CEN

45

00

C

17

Client Serverrequest

response

socket()connect()send()

recv()close()

socket()bind()listen()accept()

recv()

send()

recv()close()

Connectionestablishment

Data response

Data request

End-of-file notification

Page 18: Raspberry pi Part 23

www.techvilla.org.in

Example: Client Programming

Create stream socket (socket() )

Connect to server (connect() )

While still connected: send message to server (send() )

receive (recv() ) data from server and process it

Close TCP connection and Socket (close())

CEN

45

00

C

18

Page 19: Raspberry pi Part 23

www.techvilla.org.in

socket(): Initializing SocketGetting the file descriptor

int chat_sock;

if ((chat_sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {

perror("socket");

printf("Failed to create socket\n");

abort ();

}

1.parameter specifies protocol/address family

2.parameter specifies the socket typeOther possibilities: SOCK_DGRAM

3.parameter specifies the protocol. 0 means protocol is chosen by the OS.

CEN

45

00

C

19

Page 20: Raspberry pi Part 23

www.techvilla.org.in

IP Address Data Structurestruct sockaddr_in {

short int sin_family; // Address family

unsigned short int sin_port; // Port number

struct in_addr sin_addr; // Internet address

unsigned char sin_zero[8];

};

struct in_addr {

unsigned long s_addr; // 4 bytes

};

Padding of sin_zeros: struct sockaddr_in has same size as struct sockaddr

CEN

45

00

C

20

Page 21: Raspberry pi Part 23

www.techvilla.org.in

connect(): Making TCP Connection to Server

struct sockaddr_in sin;

struct hostent *host = gethostbyname (argv[1]);

unsigned int server_address = *(unsigned long *) host->h_addr_list[0];

unsigned short server_port = atoi (argv[2]);

memset (&sin, 0, sizeof (sin));

sin.sin_family = AF_INET;

sin.sin_addr.s_addr = server_address;

sin.sin_port = htons (server_port);

if (connect(chat_sock, (struct sockaddr *) &sin, sizeof (sin)) < 0) {

perror("connect");

printf("Cannot connect to server\n");

abort();

}

CEN

45

00

C

21

Page 22: Raspberry pi Part 23

www.techvilla.org.in

send(): Sending Packetsint send_packets(char *buffer, int buffer_len) {

sent_bytes = send(chat_sock, buffer, buffer_len, 0);

if (send_bytes < 0) {

perror (“send");

}

return 0;

}

Needs socket descriptor,Buffer containing the message, andLength of the messageCan also use write()

CEN

45

00

C

22

Page 23: Raspberry pi Part 23

www.techvilla.org.in

Receiving Packets:Separating Data in a Stream

Use records (data structures) to partition the data stream

CEN

45

00

C

23

B

Fixed length record

Fixed length record

0 1 3

C

2 94 6 87

D

5

A

receive buffer

slide through

Page 24: Raspberry pi Part 23

www.techvilla.org.in

Receiving Packetsint receive_packets(char *buffer, int buffer_len, int *bytes_read)

{

int left = buffer_len - *bytes_read;

received = recv(chat_sock, buffer + *bytes_read, left, 0);

if (received < 0) {

perror (“recv");

}

if (received <= 0) {

return close_connection();

}

*bytes_read += received;

while (*bytes_read > RECORD_LEN) {

process_packet(buffer, RECORD_LEN);

*bytes_read -= RECORD_LEN;

memmove(buffer, buffer + RECORD_LEN, *bytes_read);

}

return 0;

}

CEN

45

00

C

24

Can also use read()

buffer

*bytes_read

buffer_len

Page 25: Raspberry pi Part 23

www.techvilla.org.in

Server Programming: Simple

Create stream socket (socket() )

Bind port to socket (bind() )

Listen for new client (listen() )

While accept user connection and create a new socket

(accept() )

data arrives from client (recv() )

data has to be send to client (send() )

CEN

45

00

C

25

Page 26: Raspberry pi Part 23

www.techvilla.org.in

bind(): Assign IP and Portstruct sockaddr_in sin;

struct hostent *host = gethostbyname (argv[1]);

unsigned int server_address = *(unsigned long *) host->h_addr_list[0];

unsigned short server_port = atoi (argv[2]);

memset (&sin, 0, sizeof (sin));

sin.sin_family = AF_INET;

sin.sin_addr.s_addr = server_address;

sin.sin_port = htons (server_port);

if (bind(chat_sock, (struct sockaddr *) &sin, sizeof (sin)) < 0) {

perror("bind");

printf("Cannot bind server application to network\n");

abort();

}

CEN

45

00

C

26

Page 27: Raspberry pi Part 23

www.techvilla.org.in

bind():bind() tells the OS to assign a local IP address and local port number to the socket.

Many applications let the OS choose an IP address.

Use wildcard INADDR_ANY as local address in this case.

At server, user process must call bind() to assign a port

At client, bind() is not required since OS may assign available port and IP address

The server will get the port number of the client through the UDP/TCP packet header

Note: Each application is represented by a server port number

CEN

45

00

C

27

Page 28: Raspberry pi Part 23

www.techvilla.org.in

listen(): Wait for Connections

int listen(int sockfd, int backlog);

Puts socket in a listening state, willing to handle incoming TCP connection request.

Backlog: number of TCP connections that can be queued at the socket.

CEN

45

00

C

28

Page 29: Raspberry pi Part 23

www.techvilla.org.in