SlideShare a Scribd company logo
1 of 17
Introduction to Sockets
Ashish Gupta
TA , Intro to Networking
Jan 2004
Why do we need sockets?
Provides an abstraction for
interprocess communication
• The services provided (often by the operating
system) that provide the interface between
application and protocol software.
ApplicationApplication
Network APINetwork API
Protocol AProtocol A Protocol BProtocol B Protocol CProtocol C
Definition
Functions
–Define an “end- point” for
communication
–Initiate and accept a connection
–Send and receive data
–Terminate a connection gracefully
Examples
File transfer apps (FTP), Web browsers
(HTTP), Email (SMTP/ POP3), etc…
Types of Sockets
• Two different types of sockets :
– stream vs. datagram
• Stream socket :( a. k. a. connection- oriented socket)
– It provides reliable, connected networking service
– Error free; no out- of- order packets (uses TCP)
– applications: telnet/ ssh, http, …
• Datagram socket :( a. k. a. connectionless socket)
– It provides unreliable, best- effort networking service
– Packets may be lost; may arrive out of order (uses UDP)
– applications: streaming audio/ video (realplayer), …
Addressing
Client Server
Addresses, Ports and Sockets
• Like apartments and mailboxes
– You are the application
– Your apartment building address is the address
– Your mailbox is the port
– The post-office is the network
– The socket is the key that gives you access to the
right mailbox
Client – high level view
Create a socket
Setup the server address
Connect to the server
Read/write data
Shutdown connection
int connect_ socket( char *hostname, int port) {
int sock;
struct sockaddr_in sin;
struct hostent *host;
sock = socket( AF_ INET, SOCK_ STREAM, 0);
if (sock == -1)
return sock;
host = gethostbyname( hostname);
if (host == NULL) {
close( sock);
return -1;
}
memset (& sin, 0, sizeof( sin));
sin. sin_ family = AF_ INET;
sin. sin_ port = htons( port);
sin. sin_ addr. s_ addr = *( unsigned long *) host-> h_ addr_ list[
0];
if (connect( sock, (struct sockaddr *) &sin, sizeof( sin)) != 0) {
close (sock);
return -1;
}
return sock;
}
Resolve the host
struct hostent *gethostbyname( const char *hostname);
/*Return nonnull pointer if OK, NULL on error */
Setup up the struct
unit16_t htons(unit16_t host16bitvaule)
/*Change the port number from host byte order to
network byte order */
Connect
connect(int socketfd, const struct sockaddr * servaddr,
socket_t addrlen)
/*Perform the TCP three way handshaking*/
Hostent structure
struct hostent{
char * h_name /*official name of host*/
char ** h_aliases; /* pointer ot array of
pointers to alias name*/
int h_addrtype /* host address type*/
int h_length /* length of address */
char ** h_addr_list /*prt to array of ptrs with 
IPv4 or IPv6 address*/
}
Ipv4 socket address structure
struct socketaddr_in{
uint8_t sin_len; /*length of the structure (16)*/
sa_falimily_t sin_family /* AF_INT*/
in_port_t sin_port /* 16 bit TCP or UDP port number*/
struct in_addr sin_addr /* 32 bit Ipv4 address */
char sin_zero(8)/* unused*/
}
 
Make the socket
Socket(int family , int type, in t protocol);
return nonnegative value for OK, -1 for error
Server – high level view
Create a socket
Bind the socket
Listen for connections
Accept new client connections
Read/write to client connections
Shutdown connection
Listening on a port (TCP)
int make_ listen_ socket( int port) {
struct sockaddr_ in sin;
int sock;
sock = socket( AF_ INET, SOCK_ STREAM, 0);
if (sock < 0)
return -1;
memset(& sin, 0, sizeof( sin));
sin. sin_ family = AF_ INET;
sin. sin_ addr. s_ addr = htonl( INADDR_ ANY);
sin. sin_ port = htons( port);
if (bind( sock, (struct sockaddr *) &sin, sizeof( sin)) <
0)
return -1;
return sock;
}
Make the socket
Setup up the struct
Bind
bind(int sockfd, const struct sockaddr * myaddr, socklen_t addrlen);
/* return 0 if OK, -1 on error
assigns a local protocol adress to a socket*/
accepting a client connection (TCP)
int get_ client_ socket( int listen_ socket) {
struct sockaddr_ in sin;
int sock;
int sin_ len;
memset(& sin, 0, sizeof( sin));
sin_ len = sizeof( sin);
sock = accept( listen_ socket, (struct sockaddr *)
&sin, &sin_ len);
return sock;
}
Setup up the struct
Accept the client connection
accept(int sockefd, struct sockaddr * claddr, socklen_t * addrlen)
/* return nonnegative descriptor if OK, -1 on error
return the next completed connection from the front of the
completed connection queue.
if the queue is empty,
the process is put to sleep(assuming blocking socket)*/
Sending / Receiving Data
• With a connection (SOCK_STREAM):
– int count = send(sock, &buf, len, flags);
• count: # bytes transmitted (-1 if error)
• buf: char[], buffer to be transmitted
• len: integer, length of buffer (in bytes) to transmit
• flags: integer, special options, usually just 0
– int count = recv(sock, &buf, len, flags);
• count: # bytes received (-1 if error)
• buf: void[], stores received bytes
• len: # bytes received
• flags: integer, special options, usually just 0
– Calls are blocking [returns only after data is sent (to
socket buf) / received]
socket()
bind()
listen()
accept()
read()
write()
read()
close()
Socket()
connect()
write()
read()
close()
TCP Client
TCP Server
Well-known port
blocks until connection from client
process request
Connection establishment
Data(request)
Data(reply)
End-of-file notification
Dealing with blocking calls
• Many functions block
– accept(), connect(),
– All recv()
• For simple programs this is fine
• What about complex connection routines
– Multiple connections
– Simultaneous sends and receives
– Simultaneously doing non-networking processing
Dealing with blocking (cont..)
• Options
– Create multi-process or multi-threaded code
– Turn off blocking feature (fcntl() system call)
– Use the select() function
• What does select() do?
– Can be permanent blocking, time-limited blocking or non-
blocking
– Input: a set of file descriptors
– Output: info on the file-descriptors’ status
– Therefore, can identify sockets that are “ready for use”:
calls involving that socket will return immediately
select function call
• int status = select()
– Status: # of ready objects, -1 if error
– nfds: 1 +largest file descriptor to check
– readfds: list of descriptors to check if read-ready
– writefds: list of descriptors to check if write-ready
– exceptfds: list of descriptors to check if an
exception is registered
– Timeout: time after which select returns

More Related Content

What's hot

What's hot (20)

Socket programming in c
Socket programming in cSocket programming in c
Socket programming in c
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Socket programming in C
Socket programming in CSocket programming in C
Socket programming in C
 
Tcp sockets
Tcp socketsTcp sockets
Tcp sockets
 
Socket programming using C
Socket programming using CSocket programming using C
Socket programming using C
 
Application Layer and Socket Programming
Application Layer and Socket ProgrammingApplication Layer and Socket Programming
Application Layer and Socket Programming
 
Network Sockets
Network SocketsNetwork Sockets
Network Sockets
 
Sockets
SocketsSockets
Sockets
 
Ppt of socket
Ppt of socketPpt of socket
Ppt of socket
 
Elementary TCP Sockets
Elementary TCP SocketsElementary TCP Sockets
Elementary TCP Sockets
 
Socket programming
Socket programming Socket programming
Socket programming
 
Socket programming
Socket programmingSocket programming
Socket programming
 
123
123123
123
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
Udp socket programming(Florian)
Udp socket programming(Florian)Udp socket programming(Florian)
Udp socket programming(Florian)
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
Basic socket programming
Basic socket programmingBasic socket programming
Basic socket programming
 
Sockets
SocketsSockets
Sockets
 
socket programming
socket programming socket programming
socket programming
 
Socket Programming it-slideshares.blogspot.com
Socket  Programming it-slideshares.blogspot.comSocket  Programming it-slideshares.blogspot.com
Socket Programming it-slideshares.blogspot.com
 

Viewers also liked

IndyScribe Mini Marathon Essay
IndyScribe Mini Marathon EssayIndyScribe Mini Marathon Essay
IndyScribe Mini Marathon EssayJennifer Bortel
 
M A R R I A G E & M U T U A L B L O S S O M I N G D R
M A R R I A G E &  M U T U A L  B L O S S O M I N G   D RM A R R I A G E &  M U T U A L  B L O S S O M I N G   D R
M A R R I A G E & M U T U A L B L O S S O M I N G D Rghanyog
 
Open source: an introduction to IP and Legal
Open source: an introduction to IP and LegalOpen source: an introduction to IP and Legal
Open source: an introduction to IP and LegalBruno Lowagie
 
Business plan presentation Mom’s Biryani -The desi restaurant in Hyderabad, p...
Business plan presentation Mom’s Biryani-The desi restaurant in Hyderabad, p...Business plan presentation Mom’s Biryani-The desi restaurant in Hyderabad, p...
Business plan presentation Mom’s Biryani -The desi restaurant in Hyderabad, p...Hiba shaikh & Varda shaikh
 

Viewers also liked (7)

IndyScribe Mini Marathon Essay
IndyScribe Mini Marathon EssayIndyScribe Mini Marathon Essay
IndyScribe Mini Marathon Essay
 
M A R R I A G E & M U T U A L B L O S S O M I N G D R
M A R R I A G E &  M U T U A L  B L O S S O M I N G   D RM A R R I A G E &  M U T U A L  B L O S S O M I N G   D R
M A R R I A G E & M U T U A L B L O S S O M I N G D R
 
Open source: an introduction to IP and Legal
Open source: an introduction to IP and LegalOpen source: an introduction to IP and Legal
Open source: an introduction to IP and Legal
 
His1 intermedio tardío
His1 intermedio tardíoHis1 intermedio tardío
His1 intermedio tardío
 
Proyecto tecnologico
Proyecto tecnologicoProyecto tecnologico
Proyecto tecnologico
 
Procedure text
Procedure textProcedure text
Procedure text
 
Business plan presentation Mom’s Biryani -The desi restaurant in Hyderabad, p...
Business plan presentation Mom’s Biryani-The desi restaurant in Hyderabad, p...Business plan presentation Mom’s Biryani-The desi restaurant in Hyderabad, p...
Business plan presentation Mom’s Biryani -The desi restaurant in Hyderabad, p...
 

Similar to Sockets intro (20)

sockets_intro.ppt
sockets_intro.pptsockets_intro.ppt
sockets_intro.ppt
 
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.pptINTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
 
Sockets
Sockets Sockets
Sockets
 
L5-Sockets.pptx
L5-Sockets.pptxL5-Sockets.pptx
L5-Sockets.pptx
 
Basics of sockets
Basics of socketsBasics of sockets
Basics of sockets
 
Sockets in unix
Sockets in unixSockets in unix
Sockets in unix
 
sockets
socketssockets
sockets
 
Introduction to sockets tcp ip protocol.ppt
Introduction to sockets tcp ip protocol.pptIntroduction to sockets tcp ip protocol.ppt
Introduction to sockets tcp ip protocol.ppt
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
Socket programming-tutorial-sk
Socket programming-tutorial-skSocket programming-tutorial-sk
Socket programming-tutorial-sk
 
Os 2
Os 2Os 2
Os 2
 
Raspberry pi Part 23
Raspberry pi Part 23Raspberry pi Part 23
Raspberry pi Part 23
 
Sockets
Sockets Sockets
Sockets
 
Socket Programming Intro.pptx
Socket  Programming Intro.pptxSocket  Programming Intro.pptx
Socket Programming Intro.pptx
 
lab04.pdf
lab04.pdflab04.pdf
lab04.pdf
 
Network Prog.ppt
Network Prog.pptNetwork Prog.ppt
Network Prog.ppt
 
Net Programming.ppt
Net Programming.pptNet Programming.ppt
Net Programming.ppt
 
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونیاسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
 
Np unit2
Np unit2Np unit2
Np unit2
 
Python networking
Python networkingPython networking
Python networking
 

Recently uploaded

Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsPrecisely
 

Recently uploaded (20)

Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power Systems
 

Sockets intro

  • 1. Introduction to Sockets Ashish Gupta TA , Intro to Networking Jan 2004
  • 2. Why do we need sockets? Provides an abstraction for interprocess communication
  • 3. • The services provided (often by the operating system) that provide the interface between application and protocol software. ApplicationApplication Network APINetwork API Protocol AProtocol A Protocol BProtocol B Protocol CProtocol C Definition
  • 4. Functions –Define an “end- point” for communication –Initiate and accept a connection –Send and receive data –Terminate a connection gracefully Examples File transfer apps (FTP), Web browsers (HTTP), Email (SMTP/ POP3), etc…
  • 5. Types of Sockets • Two different types of sockets : – stream vs. datagram • Stream socket :( a. k. a. connection- oriented socket) – It provides reliable, connected networking service – Error free; no out- of- order packets (uses TCP) – applications: telnet/ ssh, http, … • Datagram socket :( a. k. a. connectionless socket) – It provides unreliable, best- effort networking service – Packets may be lost; may arrive out of order (uses UDP) – applications: streaming audio/ video (realplayer), …
  • 7. Addresses, Ports and Sockets • Like apartments and mailboxes – You are the application – Your apartment building address is the address – Your mailbox is the port – The post-office is the network – The socket is the key that gives you access to the right mailbox
  • 8. Client – high level view Create a socket Setup the server address Connect to the server Read/write data Shutdown connection
  • 9. int connect_ socket( char *hostname, int port) { int sock; struct sockaddr_in sin; struct hostent *host; sock = socket( AF_ INET, SOCK_ STREAM, 0); if (sock == -1) return sock; host = gethostbyname( hostname); if (host == NULL) { close( sock); return -1; } memset (& sin, 0, sizeof( sin)); sin. sin_ family = AF_ INET; sin. sin_ port = htons( port); sin. sin_ addr. s_ addr = *( unsigned long *) host-> h_ addr_ list[ 0]; if (connect( sock, (struct sockaddr *) &sin, sizeof( sin)) != 0) { close (sock); return -1; } return sock; } Resolve the host struct hostent *gethostbyname( const char *hostname); /*Return nonnull pointer if OK, NULL on error */ Setup up the struct unit16_t htons(unit16_t host16bitvaule) /*Change the port number from host byte order to network byte order */ Connect connect(int socketfd, const struct sockaddr * servaddr, socket_t addrlen) /*Perform the TCP three way handshaking*/ Hostent structure struct hostent{ char * h_name /*official name of host*/ char ** h_aliases; /* pointer ot array of pointers to alias name*/ int h_addrtype /* host address type*/ int h_length /* length of address */ char ** h_addr_list /*prt to array of ptrs with IPv4 or IPv6 address*/ } Ipv4 socket address structure struct socketaddr_in{ uint8_t sin_len; /*length of the structure (16)*/ sa_falimily_t sin_family /* AF_INT*/ in_port_t sin_port /* 16 bit TCP or UDP port number*/ struct in_addr sin_addr /* 32 bit Ipv4 address */ char sin_zero(8)/* unused*/ }   Make the socket Socket(int family , int type, in t protocol); return nonnegative value for OK, -1 for error
  • 10. Server – high level view Create a socket Bind the socket Listen for connections Accept new client connections Read/write to client connections Shutdown connection
  • 11. Listening on a port (TCP) int make_ listen_ socket( int port) { struct sockaddr_ in sin; int sock; sock = socket( AF_ INET, SOCK_ STREAM, 0); if (sock < 0) return -1; memset(& sin, 0, sizeof( sin)); sin. sin_ family = AF_ INET; sin. sin_ addr. s_ addr = htonl( INADDR_ ANY); sin. sin_ port = htons( port); if (bind( sock, (struct sockaddr *) &sin, sizeof( sin)) < 0) return -1; return sock; } Make the socket Setup up the struct Bind bind(int sockfd, const struct sockaddr * myaddr, socklen_t addrlen); /* return 0 if OK, -1 on error assigns a local protocol adress to a socket*/
  • 12. accepting a client connection (TCP) int get_ client_ socket( int listen_ socket) { struct sockaddr_ in sin; int sock; int sin_ len; memset(& sin, 0, sizeof( sin)); sin_ len = sizeof( sin); sock = accept( listen_ socket, (struct sockaddr *) &sin, &sin_ len); return sock; } Setup up the struct Accept the client connection accept(int sockefd, struct sockaddr * claddr, socklen_t * addrlen) /* return nonnegative descriptor if OK, -1 on error return the next completed connection from the front of the completed connection queue. if the queue is empty, the process is put to sleep(assuming blocking socket)*/
  • 13. Sending / Receiving Data • With a connection (SOCK_STREAM): – int count = send(sock, &buf, len, flags); • count: # bytes transmitted (-1 if error) • buf: char[], buffer to be transmitted • len: integer, length of buffer (in bytes) to transmit • flags: integer, special options, usually just 0 – int count = recv(sock, &buf, len, flags); • count: # bytes received (-1 if error) • buf: void[], stores received bytes • len: # bytes received • flags: integer, special options, usually just 0 – Calls are blocking [returns only after data is sent (to socket buf) / received]
  • 14. socket() bind() listen() accept() read() write() read() close() Socket() connect() write() read() close() TCP Client TCP Server Well-known port blocks until connection from client process request Connection establishment Data(request) Data(reply) End-of-file notification
  • 15. Dealing with blocking calls • Many functions block – accept(), connect(), – All recv() • For simple programs this is fine • What about complex connection routines – Multiple connections – Simultaneous sends and receives – Simultaneously doing non-networking processing
  • 16. Dealing with blocking (cont..) • Options – Create multi-process or multi-threaded code – Turn off blocking feature (fcntl() system call) – Use the select() function • What does select() do? – Can be permanent blocking, time-limited blocking or non- blocking – Input: a set of file descriptors – Output: info on the file-descriptors’ status – Therefore, can identify sockets that are “ready for use”: calls involving that socket will return immediately
  • 17. select function call • int status = select() – Status: # of ready objects, -1 if error – nfds: 1 +largest file descriptor to check – readfds: list of descriptors to check if read-ready – writefds: list of descriptors to check if write-ready – exceptfds: list of descriptors to check if an exception is registered – Timeout: time after which select returns