SlideShare a Scribd company logo
1 of 28
Socket basics
 Socket basics
 Socket details (TCP and UDP)
 Socket options
Socket Basics (1 of 2)
 An end-point for an Internet network connection
 what the application layer “plugs into”
User Application
Socket
Operating System
Transport Layer
Internet Protocol Layer
 User sees “descriptor” - integer index or object handle
 like: FILE *, or file index from open()
 returned by socket() call (more later)
 programmer cares about Application Programming Interface (API)
Socket Basics (2 of 2)
 End point determined by two things:
 Host address: IP address is Network Layer
 Port number: is Transport Layer
 Two end-points determine a connection: socket pair
 ex: 206.62.226.35,p21 + 198.69.10.2,p1500
 ex: 206.62.226.35,p21 + 198.69.10.2,p1499
Ports
 Numbers (typical, since vary by OS):
 0-1023 “reserved”, must be root
 1024 - 5000 “ephemeral”
 Above 5000 for general use
 (50,000 is specified max)
 Well-known, reserved services (see /etc/services in
Unix):
 ftp 21/tcp
 telnet 23/tcp
 finger 79/tcp
 snmp 161/udp
Transport Layer
 UDP: User Datagram Protocol
 no acknowledgements
 no retransmissions
 out of order, duplicates possible
 connectionless
 TCP: Transmission Control Protocol
 reliable (in order, all arrive, no duplicates)
 flow control
 Connection-based
 While TCP ~95% of all flows and packets, much UDP
traffic is games!
Socket Details Outline
 Structure to hold address information
 Functions pass address from user to OS
bind()
connect()
sendto()
 Functions pass address from OS to user
accept()
recvfrom()
Process to Kernel
Kernel to Process
Socket Address Structure
struct in_addr {
in_addr_t s_addr; /* 32-bit IPv4
addresses */
};
struct sockaddr_in {
unit8_t sin_len; /* length of structure
*/
sa_family_t sin_family; /* AF_INET */
in_port_t sin_port; /* TCP/UDP Port
num */
struct in_addr sin_addr; /* IPv4 address
(above) */
char sin_zero[8]; /* unused */
}
 Are also “generic” and “IPv6” socket structures
Byte Ordering
Byte Ordering Functions
TCP Client-Server
socket()
bind()
listen()
accept()
Server
socket()
connect()
send()
recv()
Client
(Block until connection)
“Handshake”
recv()
send()
Data (request)
Data (reply)
close()End-of-File
recv()
close()
“well-known”
port
socket()
int socket(int family, int type, int protocol);
Create a socket, giving access to transport layer service.
 family is one of
 AF_INET (IPv4), AF_INET6 (IPv6), AF_LOCAL (local Unix),
 AF_ROUTE (access to routing tables), AF_KEY (new, for encryption)
 type is one of
 SOCK_STREAM (TCP), SOCK_DGRAM (UDP)
 SOCK_RAW (for special IP packets, PING, etc. Must be root)
 setuid bit (-rws--x--x root 1997 /sbin/ping*)
 protocol is 0 (used for some raw socket options)
 upon success returns socket descriptor
 Integer, like file descriptor
 Return -1 if failure
bind()
 sockfd is socket descriptor from socket()
 myaddr is a pointer to address struct with:
 port number and IP address
 if port is 0, then host will pick ephemeral port
 not usually for server (exception RPC port-map)
 IP address != INADDR_ANY (unless multiple nics)
 addrlen is length of structure
 returns 0 if ok, -1 on error
 EADDRINUSE (“Address already in use”)
int bind(int sockfd, const struct sockaddr *myaddr,
socklen_t addrlen);
Assign a local protocol address (“name”) to a socket.
listen()
 sockfd is socket descriptor from socket()
 backlog is maximum number of incomplete
connections
 historically 5
 rarely above 15 on a even moderate Web server!
 Sockets default to active (for a client)
 change to passive so OS will accept connection
int listen(int sockfd, int backlog);
Change socket state for TCP server.
accept()
 sockfd is socket descriptor from socket()
 cliaddr and addrlen return protocol address from
client
 returns brand new descriptor, created by OS
 note, if create new process or thread, can create
concurrent server
int accept(int sockfd, struct sockaddr cliaddr, socklen_t
*addrlen);
Return next completed connection.
close()
 sockfd is socket descriptor from socket()
 closes socket for reading/writing
 returns (doesn’t block)
 attempts to send any unsent data
 socket option SO_LINGER
 block until data sent
 or discard any remaining data
 returns -1 if error
int close(int sockfd);
Close socket for use.
TCP Client-Serversocket()
bind()
listen()
accept()
Server
socket()
connect()
send()
recv()
Client
(Block until connection)
“Handshake”
recv()
send()
Data (request)
Data (reply)
close()End-of-File
recv()
close()
“well-known”
port
connect()
 sockfd is socket descriptor from socket()
 servaddr is a pointer to a structure with:
 port number and IP address
 must be specified (unlike bind())
 addrlen is length of structure
 client doesn’t need bind()
 OS will pick ephemeral port
 returns socket descriptor if ok, -1 on error
int connect(int sockfd, const struct
sockaddr *servaddr, socklen_t addrlen);
Connect to server.
Sending and Receiving
int recv(int sockfd, void *buff, size_t
mbytes, int flags);
int send(int sockfd, void *buff, size_t
mbytes, int flags);
UDP Client-Server
socket()
bind()
recvfrom()
Server
socket()
sendto()
recvfrom()
Client
(Block until receive datagram)
sendto()
Data (request)
Data (reply)
close()
“well-known”
port
- No “handshake”
- No simultaneous close
- No fork()/spawn() for concurrent servers!
Sending and Receiving
int recvfrom(int sockfd, void *buff, size_t mbytes, int
flags, struct sockaddr *from, socklen_t *addrlen);
int sendto(int sockfd, void *buff, size_t mbytes, int
flags, const struct sockaddr *to, socklen_t addrlen);
 Same as recv() and send() but for addr
 recvfrom fills in address of where packet came
from
 sendto requires address of where sending packet
to
connect() with UDP
 Record address and port of peer
 datagrams to/from others are not allowed
 does not do three way handshake, or connection
 “connect” a misnomer, here. Should be setpeername()
 Use send() instead of sendto()
 Use recv() instead of recvfrom()
 Can change connect or unconnect by repeating connect()
call
 (Can do similar with bind() on receiver)
Why use connected UDP?
• Send two
datagrams
unconnected:
– connect the socket
– output first dgram
– unconnect the socket
– connect the socket
– ouput second dgram
– unconnect the socket
• Send two
datagrams
connected:
– connect the socket
– output first dgram
– ouput second dgram
Socket Options
 setsockopt(), getsockopt()
 SO_LINGER
 upon close, discard data or block until sent
 SO_RCVBUF, SO_SNDBUF
 change buffer sizes
 for TCP is “pipeline”, for UDP is “discard”
 SO_RCVLOWAT, SO_SNDLOWAT
 how much data before “readable” via select()
 SO_RCVTIMEO, SO_SNDTIMEO
 timeouts
fcntl()
 ‘File control’ but used for sockets, too
 Signal driven sockets
 Set socket owner
 Get socket owner
 Set socket non-blocking
flags = fcntl(sockfd, F_GETFL, 0);
flags |= O_NONBLOCK;
fcntl(sockfd, F_SETFL, flags);
 Beware not getting flags before setting!
Concurrent Servers
 Close sock in child, newsock in parent
 Reference count for socket descriptor
Text segment
sock = socket()
/* setup socket */
while (1) {
newsock = accept(sock)
fork()
if child
read(newsock)
until exit
}
Parent
int sock;
int newsock;
Child
int sock;
int newsock;

More Related Content

What's hot

Programming TCP/IP with Sockets
Programming TCP/IP with SocketsProgramming TCP/IP with Sockets
Programming TCP/IP with Socketselliando dias
 
Socket programming
Socket programmingSocket programming
Socket programmingharsh_bca06
 
Socket programming in C
Socket programming in CSocket programming in C
Socket programming in CDeepak Swain
 
Socket programming
Socket programmingSocket programming
Socket programmingUjjwal Kumar
 
Socket programming using C
Socket programming using CSocket programming using C
Socket programming using CAjit Nayak
 
Java Socket Programming
Java Socket ProgrammingJava Socket Programming
Java Socket ProgrammingVipin Yadav
 
Socket programming using java
Socket programming using javaSocket programming using java
Socket programming using javaUC San Diego
 
A Short Java Socket Tutorial
A Short Java Socket TutorialA Short Java Socket Tutorial
A Short Java Socket TutorialGuo Albert
 
Ports & sockets
Ports  & sockets Ports  & sockets
Ports & sockets myrajendra
 
Networking lab
Networking labNetworking lab
Networking labRagu Ram
 
Lab manual cn-2012-13
Lab manual cn-2012-13Lab manual cn-2012-13
Lab manual cn-2012-13Sasi Kala
 

What's hot (20)

Np unit iii
Np unit iiiNp unit iii
Np unit iii
 
Programming TCP/IP with Sockets
Programming TCP/IP with SocketsProgramming TCP/IP with Sockets
Programming TCP/IP with Sockets
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Sockets
SocketsSockets
Sockets
 
Socket programming in C
Socket programming in CSocket programming in C
Socket programming in C
 
Socket programming
Socket programmingSocket programming
Socket programming
 
IPC SOCKET
IPC SOCKETIPC SOCKET
IPC SOCKET
 
Sockets
SocketsSockets
Sockets
 
Socket programming using C
Socket programming using CSocket programming using C
Socket programming using C
 
Np unit iv ii
Np unit iv iiNp unit iv ii
Np unit iv ii
 
Sockets
SocketsSockets
Sockets
 
Java Socket Programming
Java Socket ProgrammingJava Socket Programming
Java Socket Programming
 
Socket programming using java
Socket programming using javaSocket programming using java
Socket programming using java
 
A Short Java Socket Tutorial
A Short Java Socket TutorialA Short Java Socket Tutorial
A Short Java Socket Tutorial
 
Np unit1
Np unit1Np unit1
Np unit1
 
socket programming
socket programming socket programming
socket programming
 
Ports & sockets
Ports  & sockets Ports  & sockets
Ports & sockets
 
Networking lab
Networking labNetworking lab
Networking lab
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Lab manual cn-2012-13
Lab manual cn-2012-13Lab manual cn-2012-13
Lab manual cn-2012-13
 

Viewers also liked

Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket ProgrammingMousmi Pawar
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in JavaTushar B Kute
 
Networking Chapter 4
Networking Chapter 4Networking Chapter 4
Networking Chapter 4mlrbrown
 
Networking Chapter 5
Networking Chapter 5Networking Chapter 5
Networking Chapter 5mlrbrown
 
Easy Steps to implement UDP Server and Client Sockets
Easy Steps to implement UDP Server and Client SocketsEasy Steps to implement UDP Server and Client Sockets
Easy Steps to implement UDP Server and Client Socketsbabak danyal
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPTkamal kotecha
 
Network Packet Analysis with Wireshark
Network Packet Analysis with WiresharkNetwork Packet Analysis with Wireshark
Network Packet Analysis with WiresharkJim Gilsinn
 

Viewers also liked (20)

Jnp
JnpJnp
Jnp
 
Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket Programming
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Networking Chapter 4
Networking Chapter 4Networking Chapter 4
Networking Chapter 4
 
Networking Chapter 5
Networking Chapter 5Networking Chapter 5
Networking Chapter 5
 
Profinet Design
Profinet DesignProfinet Design
Profinet Design
 
Profinet system design - Andy Verwer
Profinet system design - Andy VerwerProfinet system design - Andy Verwer
Profinet system design - Andy Verwer
 
Profibus commissioning and maintenance - Richard Needham
Profibus commissioning and maintenance - Richard NeedhamProfibus commissioning and maintenance - Richard Needham
Profibus commissioning and maintenance - Richard Needham
 
Tcp sockets
Tcp socketsTcp sockets
Tcp sockets
 
Easy Steps to implement UDP Server and Client Sockets
Easy Steps to implement UDP Server and Client SocketsEasy Steps to implement UDP Server and Client Sockets
Easy Steps to implement UDP Server and Client Sockets
 
W4 profinet frame analysis, peter thomas
W4 profinet frame analysis, peter thomasW4 profinet frame analysis, peter thomas
W4 profinet frame analysis, peter thomas
 
Profibus and Profinet shield currents - Peter Thomas
Profibus and Profinet shield currents - Peter ThomasProfibus and Profinet shield currents - Peter Thomas
Profibus and Profinet shield currents - Peter Thomas
 
Introduction to PROFINET - Derek Lane of Wago
Introduction to PROFINET -  Derek Lane of WagoIntroduction to PROFINET -  Derek Lane of Wago
Introduction to PROFINET - Derek Lane of Wago
 
Introduction to Profibus & Profinet - Mark Freeman
Introduction to Profibus & Profinet - Mark FreemanIntroduction to Profibus & Profinet - Mark Freeman
Introduction to Profibus & Profinet - Mark Freeman
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
Wireshark - presentation
Wireshark - presentationWireshark - presentation
Wireshark - presentation
 
Network Packet Analysis with Wireshark
Network Packet Analysis with WiresharkNetwork Packet Analysis with Wireshark
Network Packet Analysis with Wireshark
 
Wireshark Basics
Wireshark BasicsWireshark Basics
Wireshark Basics
 
Ppt of socket
Ppt of socketPpt of socket
Ppt of socket
 

Similar to Socket Basics: An Introduction to Sockets

Similar to Socket Basics: An Introduction to Sockets (20)

Sockets
Sockets Sockets
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
 
L5-Sockets.pptx
L5-Sockets.pptxL5-Sockets.pptx
L5-Sockets.pptx
 
Basic socket programming
Basic socket programmingBasic socket programming
Basic socket programming
 
Network Sockets
Network SocketsNetwork Sockets
Network Sockets
 
Sockets
Sockets Sockets
Sockets
 
Sockets intro
Sockets introSockets intro
Sockets intro
 
Socket System Calls
Socket System CallsSocket System Calls
Socket System Calls
 
TCP IP
TCP IPTCP IP
TCP IP
 
Os 2
Os 2Os 2
Os 2
 
Unit 8 Java
Unit 8 JavaUnit 8 Java
Unit 8 Java
 
Socket Programming TCP:IP PPT.pdf
Socket Programming TCP:IP PPT.pdfSocket Programming TCP:IP PPT.pdf
Socket Programming TCP:IP PPT.pdf
 
sockets_intro.ppt
sockets_intro.pptsockets_intro.ppt
sockets_intro.ppt
 
socket programming
 socket programming  socket programming
socket programming
 
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
 
Application Layer and Socket Programming
Application Layer and Socket ProgrammingApplication Layer and Socket Programming
Application Layer and Socket Programming
 
Socket programming
Socket programmingSocket programming
Socket programming
 
CN_UNIT4.ppt notre knxckvj bjbDJKVHFL jb
CN_UNIT4.ppt notre knxckvj bjbDJKVHFL jbCN_UNIT4.ppt notre knxckvj bjbDJKVHFL jb
CN_UNIT4.ppt notre knxckvj bjbDJKVHFL jb
 
Udp socket programming(Florian)
Udp socket programming(Florian)Udp socket programming(Florian)
Udp socket programming(Florian)
 
Raspberry pi Part 23
Raspberry pi Part 23Raspberry pi Part 23
Raspberry pi Part 23
 

Recently uploaded

Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
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
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 

Recently uploaded (20)

Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
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
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 

Socket Basics: An Introduction to Sockets

  • 1.
  • 2. Socket basics  Socket basics  Socket details (TCP and UDP)  Socket options
  • 3. Socket Basics (1 of 2)  An end-point for an Internet network connection  what the application layer “plugs into” User Application Socket Operating System Transport Layer Internet Protocol Layer  User sees “descriptor” - integer index or object handle  like: FILE *, or file index from open()  returned by socket() call (more later)  programmer cares about Application Programming Interface (API)
  • 4. Socket Basics (2 of 2)  End point determined by two things:  Host address: IP address is Network Layer  Port number: is Transport Layer  Two end-points determine a connection: socket pair  ex: 206.62.226.35,p21 + 198.69.10.2,p1500  ex: 206.62.226.35,p21 + 198.69.10.2,p1499
  • 5. Ports  Numbers (typical, since vary by OS):  0-1023 “reserved”, must be root  1024 - 5000 “ephemeral”  Above 5000 for general use  (50,000 is specified max)  Well-known, reserved services (see /etc/services in Unix):  ftp 21/tcp  telnet 23/tcp  finger 79/tcp  snmp 161/udp
  • 6. Transport Layer  UDP: User Datagram Protocol  no acknowledgements  no retransmissions  out of order, duplicates possible  connectionless  TCP: Transmission Control Protocol  reliable (in order, all arrive, no duplicates)  flow control  Connection-based  While TCP ~95% of all flows and packets, much UDP traffic is games!
  • 7. Socket Details Outline  Structure to hold address information  Functions pass address from user to OS bind() connect() sendto()  Functions pass address from OS to user accept() recvfrom()
  • 10. Socket Address Structure struct in_addr { in_addr_t s_addr; /* 32-bit IPv4 addresses */ }; struct sockaddr_in { unit8_t sin_len; /* length of structure */ sa_family_t sin_family; /* AF_INET */ in_port_t sin_port; /* TCP/UDP Port num */ struct in_addr sin_addr; /* IPv4 address (above) */ char sin_zero[8]; /* unused */ }  Are also “generic” and “IPv6” socket structures
  • 13. TCP Client-Server socket() bind() listen() accept() Server socket() connect() send() recv() Client (Block until connection) “Handshake” recv() send() Data (request) Data (reply) close()End-of-File recv() close() “well-known” port
  • 14. socket() int socket(int family, int type, int protocol); Create a socket, giving access to transport layer service.  family is one of  AF_INET (IPv4), AF_INET6 (IPv6), AF_LOCAL (local Unix),  AF_ROUTE (access to routing tables), AF_KEY (new, for encryption)  type is one of  SOCK_STREAM (TCP), SOCK_DGRAM (UDP)  SOCK_RAW (for special IP packets, PING, etc. Must be root)  setuid bit (-rws--x--x root 1997 /sbin/ping*)  protocol is 0 (used for some raw socket options)  upon success returns socket descriptor  Integer, like file descriptor  Return -1 if failure
  • 15. bind()  sockfd is socket descriptor from socket()  myaddr is a pointer to address struct with:  port number and IP address  if port is 0, then host will pick ephemeral port  not usually for server (exception RPC port-map)  IP address != INADDR_ANY (unless multiple nics)  addrlen is length of structure  returns 0 if ok, -1 on error  EADDRINUSE (“Address already in use”) int bind(int sockfd, const struct sockaddr *myaddr, socklen_t addrlen); Assign a local protocol address (“name”) to a socket.
  • 16. listen()  sockfd is socket descriptor from socket()  backlog is maximum number of incomplete connections  historically 5  rarely above 15 on a even moderate Web server!  Sockets default to active (for a client)  change to passive so OS will accept connection int listen(int sockfd, int backlog); Change socket state for TCP server.
  • 17. accept()  sockfd is socket descriptor from socket()  cliaddr and addrlen return protocol address from client  returns brand new descriptor, created by OS  note, if create new process or thread, can create concurrent server int accept(int sockfd, struct sockaddr cliaddr, socklen_t *addrlen); Return next completed connection.
  • 18. close()  sockfd is socket descriptor from socket()  closes socket for reading/writing  returns (doesn’t block)  attempts to send any unsent data  socket option SO_LINGER  block until data sent  or discard any remaining data  returns -1 if error int close(int sockfd); Close socket for use.
  • 19. TCP Client-Serversocket() bind() listen() accept() Server socket() connect() send() recv() Client (Block until connection) “Handshake” recv() send() Data (request) Data (reply) close()End-of-File recv() close() “well-known” port
  • 20. connect()  sockfd is socket descriptor from socket()  servaddr is a pointer to a structure with:  port number and IP address  must be specified (unlike bind())  addrlen is length of structure  client doesn’t need bind()  OS will pick ephemeral port  returns socket descriptor if ok, -1 on error int connect(int sockfd, const struct sockaddr *servaddr, socklen_t addrlen); Connect to server.
  • 21. Sending and Receiving int recv(int sockfd, void *buff, size_t mbytes, int flags); int send(int sockfd, void *buff, size_t mbytes, int flags);
  • 22. UDP Client-Server socket() bind() recvfrom() Server socket() sendto() recvfrom() Client (Block until receive datagram) sendto() Data (request) Data (reply) close() “well-known” port - No “handshake” - No simultaneous close - No fork()/spawn() for concurrent servers!
  • 23. Sending and Receiving int recvfrom(int sockfd, void *buff, size_t mbytes, int flags, struct sockaddr *from, socklen_t *addrlen); int sendto(int sockfd, void *buff, size_t mbytes, int flags, const struct sockaddr *to, socklen_t addrlen);  Same as recv() and send() but for addr  recvfrom fills in address of where packet came from  sendto requires address of where sending packet to
  • 24. connect() with UDP  Record address and port of peer  datagrams to/from others are not allowed  does not do three way handshake, or connection  “connect” a misnomer, here. Should be setpeername()  Use send() instead of sendto()  Use recv() instead of recvfrom()  Can change connect or unconnect by repeating connect() call  (Can do similar with bind() on receiver)
  • 25. Why use connected UDP? • Send two datagrams unconnected: – connect the socket – output first dgram – unconnect the socket – connect the socket – ouput second dgram – unconnect the socket • Send two datagrams connected: – connect the socket – output first dgram – ouput second dgram
  • 26. Socket Options  setsockopt(), getsockopt()  SO_LINGER  upon close, discard data or block until sent  SO_RCVBUF, SO_SNDBUF  change buffer sizes  for TCP is “pipeline”, for UDP is “discard”  SO_RCVLOWAT, SO_SNDLOWAT  how much data before “readable” via select()  SO_RCVTIMEO, SO_SNDTIMEO  timeouts
  • 27. fcntl()  ‘File control’ but used for sockets, too  Signal driven sockets  Set socket owner  Get socket owner  Set socket non-blocking flags = fcntl(sockfd, F_GETFL, 0); flags |= O_NONBLOCK; fcntl(sockfd, F_SETFL, flags);  Beware not getting flags before setting!
  • 28. Concurrent Servers  Close sock in child, newsock in parent  Reference count for socket descriptor Text segment sock = socket() /* setup socket */ while (1) { newsock = accept(sock) fork() if child read(newsock) until exit } Parent int sock; int newsock; Child int sock; int newsock;