Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25...

61
1 Dr. Martin Land Application Layer Computer Networks — Hadassah College — Fall 2015 Application Layer

Transcript of Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25...

Page 1: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

1Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Application

Layer 

Page 2: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

2Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Application LayerApplication layer

Application layer issuesWhat data transport service does application need?

Quality of service (QoS)Measurable network parametersQoS requirements determine transport requirements

How does application hand data to transport layer for delivery?Socket interface

OS call opens Internet connection to program on remote nodeSocket API — application sees remote program as open file

"The user runs an application program.  The program selects the data transport service it needs — either a sequence of data messages or a continuous stream of data — and hands application data to the Transport Layer for delivery."

RFC 4949 — Internet Security Glossary

Page 3: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

3Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Quality of Service (QoS) Network parameters

Bit error rate (BER)< 10-9 on fiber optic cable< 10-3 on wireless

Packet loss rateDepends on congestion control policy

Error control

Dynamic variations inData rate / propagation delay ΔTtrans

Queuing delay ΔTQ

Processing delay ΔTproc

Delay variation(jitter)

End-to-end transmission time for one bitHigh data rate ⇒ lower transmission delay Ttrans

Congestion / priority ⇒ longer queuing delay TQ

Datagram service ⇒ longer processing delay Tproc

Delay

Physical transmission speed in bpsData rate

Page 4: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

4Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

QoS and Network PoliciesData Rate

DelayTimeDelay

Variation

ErrorControl

TransmissionSpeed

AccessDelay

CongestionControl

PriorityControl

ConnectionType

Page 5: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

5Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

QoS Requirements for Various Services

Service  Speed Error  Control 

Delay Delay  

Variation 

e‐mail  —  good  —  — 

file transfer 

NFS 

database access 

reasonable  maximum  reasonable  reasonable 

voice   fast  good   very small  very small 

video 

real time control very fast  good  very small  very small 

  

Page 6: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

6Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

QoS and Transport Trade-Off

Reliable TransportGenerally preferred when possible

Unreliable TransportUsed when

Some data loss tolerable Delay or jitter intolerableExample — video delivery

Datagram StreamSocket type

None Error correction, packet ordering, congestion control, session state

management

Processing overhead

Connectionless Connection-orientedConnection

No error correction Error-freeError control

UDPTCPProtocol

Unreliable TransportReliable Transport

Page 7: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

7Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Application / Transport InterfaceApplication requests service from transport layer

Receives Application layer PDU — data for transportInterface Control Information (ICI)

Service requirements Local + remote endpoints

Prepare Transport service requirementsData for transportLocal endpoint — node address + service portRemote endpoint — node address + service port

Transport Layer

Application Layer

Page 8: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

8Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Berkeley Sockets Networking API

De facto standard on Unix / Linux / Apple systemsApplication performs communication like file I/O

Description of connection between client / server processesProtocol + source endpoint + destination endpoint

Association

Address + port of software process (local / remote)Endpoint

Remote (foreign) nodeDestination

Local nodeSource

Internet address of local / remote node Address

OS resources associated with protocol + endpointServer side — socket ID points to service offered to remote nodesClient side — socket ID points to connection to remote service

Socket

ID number of client / server softwarePort

Page 9: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

9Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Socket System Calls

Open connection to remote service and associate with socket

Client Side

Connect

Associate port with socketBind

Terminate socket

Local process reads data from socket (OS buffer from remote node)

Local process sends data to socket (OS forwards to remote node)

Create new socket associated with protocol at local address

Client and Server

Socket

Send

Receive

Close

Accept remote connection to local service socketAccept

Prepare to accept remote connections to local service socketListen

Server Side

Page 10: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

10Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Socket Calls — Between App and OSSocket, Bind

OS creates resources for network connectionOS returns to App socket descriptor (socket ID)

Listen Server OS makes service available

ConnectClient OS attempts connection to service

AcceptServer OS creates new connection socketServer OS returns new descriptor to AppListen socket continues to listen

SendApp sends data to OS, pointed at socketOS transmits data on associated connection

ReceiveApp requests data from OS socket bufferOS returns data to AppPHY

OS

App

call

return

SocketCalls

OSActivity

Socket ID points to OS resources

Page 11: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

11Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

ConnectionServerClient

= socket(domain, type, protoc_ID col)

connect( , service_endpoc_ID int)

connection set‐up

address type service type

= socket(domas_ in, type, protID ocol)

bind( , s_endpoint, s_endpoint_s_ID len)

s_IDlisten( , backlog)

= accept( , c_endpoint, endpoint_s s_ID len)

send( , data, len, s flags)

data

receive( , buffer, len, flc_ID ags)

bind( , c_endpoint, c_endpoint_c_ID len) If client skips  bind()OS sets a default port

Page 12: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

12Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Node AddressesIPv4 — Internet Protocol version 4

32-bit address 4 octets (bytes) written in decimal — A.B.C.D

0 ≤ A, B, C, D ≤ 255Disconnected intranet addresses 10.x.x.x and 192.168.0.x

Usable in any local intranetNot used in global Internet (between intranets)Network Address Translation (NAT) at gateway router

Permits sharing one external IP address for entire Intranet

127.0.0.1Loopback address used for testingAddress alias for "this node"

IPv6 — Internet Protocol version 6128-bit address Repairs service flaws in IPv4

Page 13: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

13Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

PortsClient (source) port

Client can assign any unused port number 1024 ≤ port ≤ 65,535Well-known port (destination port) — standard services

Assigned by Internet Assigned Numbers Authority (IANA) Examples

Domain Name Service53dns

Comment PortService

http protocol over TLS/SSL443https

Internet Message Access Protocol143imap

Post Office Protocol ‐ Version 3110pop3

World Wide Web HTTP80http

Simple Mail Transfer25smtp

Telnet23telnet

The Secure Shell (SSH) Protocol22ssh

File Transfer [Control]21ftp

File Transfer [Default Data]20ftp‐data

Page 14: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

14Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

TelnetTelnet Protocol — RFC 854

Text-oriented reliable communication over TCPTelnet client forwards user text to serverTelnet server provides remote login

Command line user interface (CLI) on remote node

Telnet programImplements telnet client protocolConnect to telnet server (port 23) on server node

$ telnet node

Connect to port port on server node$ telnet node port

Example Connect to Google web server on HTTP (port 80)$ telnet www.google.com 80

Page 15: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

15Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

HTTP — Hypertext Transfer ProtocolStateless transaction protocol

Client request formulated in ASCII (printable) textServer response formulated in MIME structuresNo stored data on prior transactions

MIME — Multipurpose Internet Mail ExtensionsText in non-ASCII character setsNon-text attachmentsMultipart message bodies

HTTP/1.0Non-persistent connection

One transaction per TCP connection

HTTP/1.1Persistent connection

Multiple transactions on same TCP socket

Pipelined transactionsMultiple requests without waiting for response

Page 16: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

16Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

HTTP Requests Simple requests

Defined in HTTP1.1 for HTTP/1.0 compatibilityRequest: single line — GET, POST, HEADResponse: raw page without MIME headers

Full requestsMulti-line request format

Request-Line format

Incidence Line

OptionalMessage-body

Blank lineCRLF

Zero or moreMessage-header CRLF

One Request-Line

CRLFHTTP-VersionSpRequest-URISpMethod

Function Method

tunneling via proxyCONNECT

echo back messageTRACE

delete pageDELETE

append to resourcePOST

store pagePUT

get page headerHEAD

get pageGET

Page 17: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

17Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Full Request Example

CRLF

Header lines

Request line

\r\n

Connection: keep-alive\r\n

Keep-Alive: 115\r\n

Accept-Charset: ISO-8859-1,utf-8;q=0.7\r\n

Accept-Encoding: gzip,deflate\r\n

Accept-Language: en-us,en;q=0.5\r\n

Accept: text/html,application/xhtml+xml\r\n

User-Agent: Firefox/3.6.10\r\n

Host: www-net.cs.umass.edu\r\n

GET /index.html HTTP/1.1\r\n

Page 18: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

18Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

HTTP ResponsesGeneral structure

Status line structure

ExampleHTTP/1.1 200 OK\r\nDate: Sun, 26 Sep 2010 20:09:20 GMT\r\nServer: Apache/2.0.52 (CentOS)\r\nLast-Modified: Tue, 30 Oct 2007 17:00:02 GMT\r\nETag: "17dc6-a5c-bf716880"\r\nAccept-Ranges: bytes\r\nContent-Length: 2652\r\nKeep-Alive: timeout=10, max=100\r\nConnection: Keep-Alive\r\nContent-Type: text/html; charset=ISO-8859-1\r\n\r\ndata data data data data ...

Zero or moreData

Zero or moremessage-header CRLF

One Status Line

IncidenceLine

CRLFdescriptionSpstatus codeSpHTTP version

Headers

Status line

Data

Page 19: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

19Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

HTTP Response Codes

HTTP Version not supported505Forbidden403

Gateway Time-out504Payment Required402

Service Unavailable503Unauthorized401

Bad Gateway502Bad Request400

Not Implemented501Temporary Redirect307

Internal Server Error500Use Proxy305

Expectation Failed417Not Modified304

Requested range not satisfiable416See Other303

Unsupported Media Type415Found302

Request-URI Too Large414Moved Permanently301

Request Entity Too Large413Multiple Choices300

Precondition Failed412Partial Content206

Length Required411Reset Content205

Gone410No Content204

Conflict409Non-Authoritative Information203

Request Time-out408Accepted202

Proxy Authentication Required407Created201

Not Acceptable406OK200

Method Not Allowed405Switching Protocols101

Not Found404Continue100

Page 20: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

20Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Telnet into Web Server$ telnet www.hadassah.ac.il 80Trying 212.179.79.228...Connected to hathi.hadassah.ac.il.Escape character is '^]'.GET / HTTP/1.0

HTTP/1.1 301 Moved PermanentlyContent-Length: 158Content-Type: text/htmlLocation: http://www.hadassah.ac.il/main.htmlServer: Microsoft-IIS/6.0X-Powered-By: ASP.NETDate: Tue, 05 Jul 2011 09:01:35 GMTConnection: close

<head><title>Document Moved</title></head><body><h1>Object Moved</h1>This document may be found <a

HREF="http://www.hadassah.ac.il/main.html">here</a></body>Connection closed by foreign host.

open connection to Hadassah web server

Simple request for index page CRLF

Server response

Page 21: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

21Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

emailSimple Mail Transfer Protocol (SMTP)

Defined in RFC 5321

OS

SMTP clientLocal user mailboxPOP/IMAP server

OS

SMTP server

mail

Post Office Protocol (POP3)Defined in RFC 1939 + 2449 + 1734Server access with user authenticationDownload / delete messages

Internet Message Access Protocol (IMAP)Defined in RFC 2060Server access with user authenticationRead / delete / organize messages

Page 22: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

22Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

email Use CasesUnix/Linux mail

Mailbox assigned to each user accountSMTP client sends message → SMTP server → local user mailbox

Outlook/Thunderbird mailUser mailboxes on mail server (host)Outlook/Thunderbird runs SMTP client + POP3/IMAP clientsSMTP client sends message → SMTP server on user-1 mail hostSMTP client sends message → SMTP server on user-2 mail hostPOP3/IMAP client gets message ←→ POP3/IMAP server on mail host

WebmailUser composes mail on web serviceWeb service sends mail from SMTP client → user-2 SMTP serverUser read mail on web service IMAP client

user‐1 mail host mail host user‐2SMTP SMTP POP3

SMTPclient

SMTPclient

POPclient

SMTPserver

SMTPserver

POPserver

Page 23: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

23Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Telnet to SMTP Server$ telnet mail.bezeqint.net 25Trying 192.115.106.15...Connected to mail.bezeqint.net.Escape character is '^]'.220 sa14.bezeqint.net ESMTP Bezeq International SMTP out Mail Server

helo [email protected]

250 sa14.bezeqint.netmail from:<[email protected]>250 2.1.0 Okrcpt to:<[email protected]>250 2.1.5 Okdata354 End data with <CR><LF>.<CR><LF>this is a line of a message

.

250 2.7.1 Ok, discarded, id=13560-10 - SPAM500 5.5.2 Error: bad syntaxquit221 2.0.0 ByeConnection closed by foreign host.

open connection to Bezeqint SMTP server

introduce user

begin new message

recipient

begin message body

message body

give up

busted!

Page 24: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

24Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Telnet to POP3 Server — 1$ telnet mail.bezeqint.net 110Trying 192.115.106.15...Connected to mail.bezeqint.net.Escape character is '^]'.+OK Bezeqint POP3PROXY Ready 00020c4fuser **********+OK USER ********** set, matepass **********+OK Maildrop locked and readylist+OK scan listing follows1 5007802 4432.

open connection to Bezeqint POP3 server

POP3 commands

end sessionQUIT

undeleteRSET

deleteDELE msg 

download header + linesTOP msg lines

download messageRETR msg 

size of messagesLIST

number of messagesSTAT

passwordPASS

user idUSER

Page 25: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

25Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Telnet to POP3 Server — 2top 1 0+OK 500780 octetsReturn-Path: <[email protected]>Received: from m5.bezeqint.net (m5.bezeqint.net [192.115.104.85])

by mas27.bezeqint.net (MOS 3.8.6-GA)with ESMTP id HRK58842;Mon, 4 Jul 2011 14:19:51 +0300 (IDT)

Received: from baloo-new.hadassah-col.ac.il (EHLO bagheera.hadassah.ac.il) ([212.179.79.229])by m5.bezeqint.net (MOS 4.1.9-GA FastPath queued)with ESMTP id KHN24377;Mon, 04 Jul 2011 14:19:50 +0300 (IDT)

Content-class: urn:content-classes:messageMIME-Version: 1.0Content-Type: multipart/mixed;

boundary="----_=_NextPart_001_01CC3A3C.603293DC"Subject: =?windows-1255?B?5Obu8OQ=?=Date: Mon, 4 Jul 2011 14:18:25 +0300Message-ID: <27B903C4A7521E47B76F1C36B1CE5ED903044469@arathorn.hadassah-col.ac.il>From: "Simcha Rozen" <[email protected]>To: <[email protected]>, <[email protected]>, <[email protected]>,

<[email protected]>.quit+OKConnection closed by foreign host.

request header of message 1 with 0 lines of message body

end session

Page 26: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

26Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

File TransferFile Transfer Protocol (FTP)

Transfer files between client and serverSeparate control (port 21) and data (port 20) connections

FTP server Accesses file system on server nodeProvides Unix-like directory services to clientOpens, reads, copies file contents to service socketCreates, writes file contents from client socket

FTP clientRequests directory servicesSends / receives files

Active modeClient sends client IP address and port number to server Server initiates TCP data connection

Passive modeServer sends IP address and port number to client Client initiates TCP data connection

Page 27: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

27Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

FTP CommandsAbout 80 commands

ftp> helpCommands may be abbreviated. Commands are:! dir mdelete qc site$ disconnect mdir sendport sizeaccount exit mget put statusappend form mkdir pwd structascii get mls quit systembell glob mode quote suniquebinary hash modtime recv tenexbye help mput reget tickcase idle newer rstatus tracecd image nmap rhelp typecdup ipany nlist rename userchmod ipv4 ntrans reset umaskclose ipv6 open restart verbosecr lcd prompt rmdir ?delete ls passive runiquedebug macdef proxy send

Some common commands

Change local directorylcdTransfer multiple files using wildcardsmget / mputTransfer local file to remote system putTransfer remote file to local systemgetTerminate ftp sessioncloseConnect to remote ftpopenSend command to local system!

Page 28: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

28Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Domain Name System (DNS)Address resolution

Converts between node name and node IP address

$ nslookup www.hadassah.ac.ilServer: 10.0.0.180Address: 10.0.0.180#53

Non-authoritative answer:Name: hathi.hadassah.ac.ilAddress: 212.179.79.228

$ nslookup 212.179.79.228Server: 10.0.0.180Address: 10.0.0.180#53

Non-authoritative answer:228.79.179.212.in-addr.arpaname = bzq-179-79-228.static.bezeqint.net

Page 29: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

29Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Domain Name SpaceHierarchal tree

Tanenbaum, p. 623

hathi.hadassah.ac.il

)ISOC-IL(איגוד האינטרנט הישראלי

)א"מ חב (הבינאוניברסיטאימ רכז ה חישובים

Hadassah College domain

Named server in Hadassah College domain

countryil

academicac

organizationhadassah

serverhathi

Page 30: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

30Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Address Resolution Hierarchy

Local Node

NameCache

Resolverrequest

response

Resolver

Default Name Server

Foreign Name Server

request

response

Local Hierarchy

Forwarder Higher in hierarchy

Page 31: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

31Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Hierarchical Name ResolutionHost OS

Resolves addresses using default name server

c:\>ipconfig /allEthernet adapter Ethernet:

...IP Address. . . . . . . . . : 10.0.0.5Default Gateway . . . . . . : 10.0.0.138DNS Servers . . . . . . . . : 10.0.0.11

c:\>nslookup www.hadassah.ac.ilServer: dns.homeAddress: 10.0.0.11Non-authoritative answer:Address: 212.179.79.228Name: www.hadassah.ac.il

$ cat /etc/resolv.conf# Generated by NetworkManagersearch homenameserver 10.0.0.180nameserver 10.0.0.11

$ nslookup www.hadassah.ac.ilServer: 10.0.0.11Address: 10.0.0.11#53

Non-authoritative answer:www.hadassah.ac.il Name: www.hadassah.ac.ilAddress: 212.179.79.228

LinuxWindows XP

DNS serverResolves refers unknown address up the tree

$ cat /etc/bind/named.conf.options

forwarders { 192.115.106.10;62.219.186.7;

};

Page 32: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

32Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Resources Records (RR)

RDLENGTHRR-specific dataRDATA

2Length of RDATA fieldRDLENGTH4Time to liveTTL2Class code (class = Internet)CLASS

2RR type (see table)TYPE

Length of node nameNode nameNAME

Length (octets)DescriptionRR Field

Pointer to canonical name (for reverse DNS)pointerPTR12List of email agents for that domainmail exchangeMX15

Authoritative information about DNS zone: primary name server, email of domain, ...

start of authoritySOA6

Authoritative DNS name servers for domainname serverNS2

16

5

1

Type Value

Additional information

Canonical node name

32-bit IPv4 address

Function

text

name

address

Description

TXT

CNAME

A

Field Name

Page 33: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

33Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

DNS Request / Response Packets

supplied by questioner and echoed unchanged by responder

number of resource records in additional records section

number of name server resource records in authority section

number of resource records in answer section

number of entries in question section

ARCOUNT

NSCOUNT

ANCOUNT

QDCOUNT

RCODEres3res2res1RARDTCAAOPCODEQR

Message ID

1514131211109876543210

Response type0 No error condition 1 Format error 2 Server failure3 Name Error 4 Not Implemented 5 Refused

RCODE

1 = Recursion AvailableRA1 = Recursion DesiredRD1 = Message truncated (too long for channel)TC1 = Authoritative AnswerAA

Request operation type 0 = standard query 1 = inverse query 2 = status request

OPCODE

Query = 0 / Response = 1QR

Page 34: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

34Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Client Socket in PerlPerl IO::Socket package

Provides simplified implementation of socket APIOpen new socket

use IO::Socket;$sock = IO::Socket::INET->new(

Proto => "Protocol",PeerAddr => "Destination Address",PeerPort => "Port Number",)

or die "cannot connect to port at localhost";

Read data from server$data = <$sock>;print $data;

Send data to serverprint $sock "hello server!\n";

Page 35: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

35Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Perl Client Socket Example

#!/usr/bin/perluse IO::Socket;

$sock = IO::Socket::INET->new(Proto => "tcp",PeerAddr => "www.hadassah.ac.il",PeerPort => "80",)

or die "Couldn’t connect!";

print $sock "GET /main.html HTTP/1.0\n\n";

print <$sock>;

close($sock);

include perl Socket packageopen connection to Hadassah web serverOS returns socket descriptor to variable $sock

send server request for home page

display on screen data returned from server

close connection

Read Hadassah College homepage

Page 36: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

36Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Perl Client Socket Example

#!/usr/bin/perluse IO::Socket; $sock = IO::Socket::INET->new(

Proto => "tcp",PeerAddr => "www.hadassah.ac.il",PeerPort => "80",)

or die "Couldn’t connect!";print $sock "GET /main.html HTTP/1.0\n\n";print <$sock>;close($sock);

Read Hadassah College homepage

Save file as hadassah.pl

$ perl hadassah.plHTTP/1.1 302 FoundCache-Control: privateContent-Type: text/html; charset=utf-8Location: http://www.hadassah.ac.il/en/error-page/X-AspNet-Version: 4.0.30319Date: Wed, 19 Nov 2014 17:47:18 GMTConnection: close

<html><head><title>Object moved</title></head><body><h2>Object moved to <ahref="http://www.hadassah.ac.il/en/error-page/">here</a>.</h2></body></html>

At command line

Page 37: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

37Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Server Socket in Perl#!/usr/bin/perluse IO::Socket;

$sock = IO::Socket::INET->new(LocalHost => 'IP_address',

LocalPort => port_number,

Listen => 1,

Reuse => 1,

Proto => 'tcp') || die "Error\n";

$client = $sock->accept();

assign server address

assign service port number

listen system call

reuse port number when process stops

protocol = TCP

accept system call

open listening socket on server

Page 38: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

38Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Perl Server Socket Example#!/usr/bin/perl$flag = "1";use IO::Socket; $sock = IO::Socket::INET->new(

LocalHost => '127.0.0.1',LocalPort => 1234, Listen => 1, Reuse => 1, Proto => 'tcp') || die "Error creating socket\n";

$client = $sock->accept(); while($flag == "1") { $line = <$client>;print $line; print $client "Received\n"; if ($line =~ /bye/) {$flag = "0";}

} close($sock);

Server Prints data from client EchoesReceivedCloses on data bye

In CLI run perl script$perl servlet.pl

In second CLI enter:$telnet 127.0.0.1 1234Trying 127.0.0.1...Connected to 127.0.0.1.Escape character is '^]'.

LOOPBACK ADDRESS (for testing)127.0.0.1

Local calls on this machine

Page 39: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

39Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Sockets in C

Header library Constants, data type, data structures, system calls

ConstantsProtocol parameters / sizes, address parameters /sizes, …

Data structuresstruct templates for addresses, ports, protocols, …addrinfo

struct template for connection informationProgrammer provides partial endpoint information to instance hintsSystem provides remaining information in instance res

System callsByte order for network standardEndpoint parameters based on OS operations Standard socket calls

Socket, bind, listen, accept, send, receive

Overview

Page 40: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

40Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Sockets in CHeaders

Functions for translating protocol and host names into numeric addresses

<netdb.h>

Functions for manipulating numeric IP addresses<arpa/inet.h >

PF_UNIX / PF_LOCAL address family

For communication between programs on same computer

<sys/un.h>

PF_INET / PF_INET6 protocol familiesAF_INET / AF_INET6 address families

Theory — multiple AF addresses per protocol familyPractice — AF = FP

<netinet/in.h>

Socket functions and data structures<sys/socket.h>

Page 41: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

41Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Sockets in CSome data types and constants

Datagram (connectionless) serviceSOCK_DGRAM

Allow OS to set local IP addressAI_PASSIVE

Stream (connection oriented) serviceSOCK_STREAM

Length of IP address string on OS INET_ADDRSTRLEN

Data type for length of data messagesize_t

Data type for size of endpoint structuresocklen_t

struct template for building sockaddrsockaddr_in

struct template for endpoint (address+port)sockaddr

struct template for description of connectionaddrinfo

IP version 6PF_INET6 = AF_INET6

IP protocol familyPF_INET = AF_INET

Page 42: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

42Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Sockets in CPredefined address information (ai) template

pointer to linked AI struct

canonical hostname

pointer to endpoint struct

size of  ai_addr in bytes

protocol / 0

SOCK_STREAM / SOCK_DGRAM

AF_INET for IPv4

AI_PASSIVE—OS sets address

AI_CANONNAME— use hostname

};

struct addrinfo *ai_next;

char *ai_canonname;

struct sockaddr *ai_addr;

socklen_t ai_addrlen;

int ai_protocol;

int ai_socktype;

int ai_family;

int ai_flags;

struct addrinfo {

Page 43: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

43Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Sockets in CPredefined endpoint information templates

sin_zero[8];

sin_addr;

sin_port;

sin_family;

sa_data[14];

sa_family;

};

zeros (padding)unsigned char

IP address as structstruct in_addr

Port numberunsigned short int

AF_INETshort int

Access sockaddr fieldsstruct sockaddr_in {

struct sockaddr {

Socket address familyAF_INET (for IPv4)

unsigned short

};

protocol address

Port  = 2 bytes

IP address = 4 bytes (IPv4)

Padding = 8 bytes (zeros)

char

Page 44: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

44Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Sockets in C

int getaddrinfo(const char *node,

const char *service,

const struct addrinfo *hints,

struct addrinfo **res);

getaddrinfo()

Status integer — check with function gai_strerror()Return

Output instance of addrinfo holding info set by OS resolutionres

Input instance of addrinfo holding info set by Apphints

Port number (client's requested service or server's offered service)NULL leaves service uninitialized

service

Remote node addressNULL (OS provides local node address)

node

System call Input instance (hints) ⎯→ output instance (res) using OS information

Page 45: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

45Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

addrinfo

ClientRequires addrinfo instance to describe remote service

Writes remote server address string + remote service to hintsgetaddrinfo converts hints ⎯→ res using OS information

ServerRequires addrinfo instance to describe local service

Writes NULL address + local service to hintsgetaddrinfo converts hints ⎯→ res using OS information

sockaddrgetaddrinfo writes addrinfo.sockaddr as HEX endpoint

sockaddr_inUser copies addrinfo.sockaddr ⎯→ sockaddr_inReads port and IP address as separate members

Sockets in CWho uses address information (ai) templates?

Page 46: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

46Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Sockets in Cgetaddrinfo() example — setting endpoint for LOCAL HTTP server 

fprintf(stderr, "getaddrinfo error: %s\n",gai_strerror(status));

nonzero status — check error

OS provides IP address

TCP stream

IPv4

initialize hints to zero

local_res = output struct

hints = input struct

status = getaddrinfo(NULL, "http", &hints, &local_res)

system fills local_res with local service endpoint = local_IP:http using hints and OS data

hints.ai_flags = AI_PASSIVE;

hints.ai_socktype = SOCK_STREAM;

hints.ai_family = AF_INET;

memset(&hints, 0, sizeof hints);

fill hints with partial information

struct addrinfo *local_res;

struct addrinfo hints;

int status;

Page 47: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

47Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Sockets in Cgetaddrinfo() example — setting endpoint for REMOTE server 

fprintf(stderr, "getaddrinfo error: %s\n",gai_strerror(status));

nonzero status — check error

OS provides IP address

TCP stream

IPv4

initialize hints to zero

remote_res = output struct

hints = input struct

status = getaddrinfo(remote_IP, 80, &hints, & remote _res)

system fills remote_res with local service endpoint = remote_IP:80 using hints and OS data

hints.ai_flags = AI_PASSIVE;

hints.ai_socktype = SOCK_STREAM;

hints.ai_family = AF_INET;

memset(&hints, 0, sizeof hints);

fill hints with partial information

struct addrinfo *remote_res;

struct addrinfo hints;

int status;

Page 48: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

48Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Sockets in C

Convert text form to struct (presentation to network)inet_pton()

Examplestruct sockaddr_in sa;

inet_pton(AF_INET, "10.0.0.1", &(sa.sin_addr));

Convert struct to text form (network to presentation)inet_ntop()

Examplechar ip4[INET_ADDRSTRLEN];struct sockaddr_in sa;

inet_ntop(AF_INET, &(sa.sin_addr), ip4, INET_ADDRSTRLEN);

Address conversion

define instance sa of struct sockaddr_in

convert address to struct and write into sa

INET_ADDRSTRLEN preset by system

convert address and write into ip4

Page 49: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

49Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Sockets in C

Big-endianInteger stored in memory with MSB in lowest addressStandard for network operations (Network Order)

Little-endianInteger stored in memory with LSB in lowest addressStandard on Intel processors

Conversion functionsConverts Host Order to Network OrderNo change if Host Order = big-endian

Byte order conversion

network to host longntohl()

network to host shortntohs()

host to network long (long = 4 bytes = 32 bits)htonl()

host to network short (short = 2 bytes = 16 bits)htons()

Page 50: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

50Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Sockets in C

/* showip.c show IP addresses for remote host */#include <stdio.h>#include <string.h>#include <sys/types.h>#include <sys/socket.h>#include <netdb.h>#include <arpa/inet.h>

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

struct addrinfo hints, *remote_res, *p; int status;char ipstr[INET_ADDRSTRLEN];if (argc != 2) {

fprintf(stderr,"usage: showip hostname\n");return 1;

}

Example for setting remote endpoint — part 1

3 instances

character array to hold IP addresses

Page 51: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

51Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Sockets in C

memset(&hints, 0, sizeof hints);

hints.ai_family = AF_INET;

hints.ai_socktype = SOCK_STREAM;

if ((status = getaddrinfo(argv[1], NULL, &hints,&remote_res)) != 0) {

fprintf(stderr, "getaddrinfo: %s\n",

gai_strerror(status));

return 2;

}

printf("IP addresses for %s:\n\n", argv[1]);

Example for setting remote endpoint — part 2

initialize hints to zero

set remote_res to system‐provided infoargv[1] = hostnameport = 0 (not set)

print error message on fail

print heading for list of addresses

set known hintsIPv4TCP

Page 52: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

52Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Sockets in C

for (p = remote_res; p != NULL; p = p->ai_next) {void *addr;char *ipver;

struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;

addr = &(ipv4->sin_addr);ipver = "IPv4";

inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr);

printf(" %s: %s\n", ipver, ipstr);

}freeaddrinfo(res);return 0;

}

Example for setting remote endpoint — part 3

loop over linked list

instance ipv4← instance p.ai_addrai_addr points to sockaddr = endpoint = IP:port

addr← IP address in p.ai_addr

convert addr = IP address to ipstr = character string

free linked list

print IPv4: ipstr

Page 53: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

53Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Sockets in C

$ showip www.google.co.ilIP addresses for www.google.co.il:

IPv4: 74.125.230.148IPv4: 74.125.230.144IPv4: 74.125.230.145IPv4: 74.125.230.146IPv4: 74.125.230.147

Running showip

Page 54: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

54Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Sockets in C

int socket(int domain, int type, int protocol);

socket() with hard coded endpoint type

int s;s = socket(PF_INET, SOCK_STREAM, 0);

Specify protocol or 0 default — TCP for STREAM or UDP for DGRAMprotocol

Service typetype

Address familydomain

PF_INET = AF_INET = IPv4SOCK_STREAM = reliable transport0 = use default service protocol — TCP for STREAM or UDP for DGRAM

No local or remote endpoint required to open socket

socket descriptor

Page 55: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

55Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Sockets in C

int socket(int domain, int type, int protocol);

int s;struct addrinfo hints, *res;

hints.ai_family = AF_INET;

hints.ai_socktype = SOCK_STREAM;

getaddrinfo("www.hadassah.ac.il", "http", &hints, &res);

// getaddrinfo(NULL, "http", &hints, &res);

s = socket(res->ai_family, res->ai_socktype,res->ai_protocol);

socket() using fields in struct res

Specify protocol or 0 default — TCP for STREAM or UDP for DGRAMprotocol

Service typetype

Address familydomain

socket call using res

set up hints

socket descriptor

client side for remote server

server side for local server

Page 56: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

56Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Sockets in C

int bind(int sockfd, const struct sockaddr *my_addr,socklen_t addrlen);

int s; struct addrinfo hints, *local_res; hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM;hints.ai_flags = AI_PASSIVE;

getaddrinfo(NULL, "http", &hints, &local_res);s = socket(local_res->ai_family, local_res->ai_socktype,

local_res->ai_protocol);

bind(s, local_res->ai_addr, local_res->ai_addrlen);

bind()

prepare hints

OS sets node IP address

bind socket to local service using ai_addressendpoint (instance of sockaddr)

resolve local address and port to local_res , open socket as server

Page 57: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

57Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Sockets in C

int listen(int sockfd, int backlog);

listen(s, backlog);

struct sockaddr_storage cliaddr;socklen_t addr_size;addr_size = sizeof cliaddr;

int accept(int sockfd, struct sockaddr *cliaddr,socklen_t *addrlen);

int c_s;

c_s = accept(s, (struct sockaddr *)&cliaddr,&addr_size);

listen() and accept()

listen on socket sallow connections ≤ backlog

sockaddr_storagestruct for connected endpoint designed for IPv4 and IPv6will be cast as sockaddr in accept()

create copy c_s of socket s for connection accept connection on socket c_scast cliaddr as sockaddr write client endpoint information to cliaddr

Page 58: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

58Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Sockets in Cconnect()

prepare hints, resolve remote addrinfo

resolve remote address and port to remote_res

int connect(int sockfd, const struct sockaddr *serv_addr,socklen_t addrlen);

int s;

struct addrinfo hints, *remote_res;

hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM;

getaddrinfo("www.google.com, "http", &hints, &remote_res);

s = socket(remote_res->ai_family, remote_res->ai_socktype,remote_res->ai_protocol);

connect(s, remote_res->ai_addr, remote_res->ai_addrlen)

open socket s for connecting to remote service using ai_address endpoint

Page 59: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

59Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Sockets in C

int send(int sockfd, const void *msg, size_t len,int flags);

char *msg = "Hello, world!";

size_t s_len,

int bytes_sent;

s_len = strlen(msg);

bytes_sent = send(c_s, msg, s_len, 0);

send()

send string on socket c_sreturns number of bytes actually sent

Page 60: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

60Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Sockets in C

int recv(int sockfd, void *buf, size_t len, int flags);

#define BUFFER_SIZE 100

char buffer[BUFFER_SIZE];

size_t r_len = BUFFER_SIZE;

int bytes_received;

bytes_received = recv(c_s, buffer, r_len, 0);

recv()

receive string on socket c_ sreturns number of bytes actually received

choose desired receive buffer size

Page 61: Application Layer · pop3 110 Post Office Protocol ‐Version 3 http 80 World Wide Web HTTP smtp 25 Simple Mail Transfer telnet 23 Telnet ssh 22 The Secure Shell (SSH) Protocol ftp

61Dr. Martin LandApplication LayerComputer Networks — Hadassah College — Fall 2015

Sockets in C

int send(int sockfd, const void *msg, size_t len,int flags);

int sendto(int sockfd, const void *msg, size_t len,

int flags, const struct sockaddr *to,

socklen_t tolen);

int recv(int sockfd, void *buf, size_t len, int flags);

int recvfrom(int sockfd, void *buf, size_t len,

int flags, struct sockaddr *from,

size_t *fromlen);

Connectionless data transfer — sendto() and recvfrom()

No accept() for local sockfdDefine source endpoint on the fly

No connect() for local sockfdDefine destination endpoint on the fly