SlideShare a Scribd company logo
1 of 28
Sockets
IMGD 4000
Outline
• Socket basics
• Socket details (TCP and UDP)
• Socket options
• Final notes
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!
Outline
• Socket basics
•Socket details (TCP and UDP)
• Socket options
• Final notes
Socket Details Outline
Unix Network Programming, W. Richard Stevens,
2nd edition, 1998, Prentice Hall
• Project 3  Links has samples
– C++, Windows and C++, Linux
– Java
• Code is very similar for Windows
• Addresses and Sockets
• TCP client-server (talk-tcp, listen-tcp)
• UDP client-server (talk-udp, listen-udp)
• Misc stuff
– setsockopt(), getsockopt()
– fcntl()
Addresses and Sockets
• Structure to hold address information
• Functions pass address from user to OS
bind()
connect()
sendto()
• Functions pass address from OS to user
accept()
recvfrom()
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
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
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-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
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);
• Same as read() and write() but for flags
– MSG_DONTWAIT (this send non-blocking)
– MSG_OOB (out of band data, 1 byte sent ahead)
– MSG_PEEK (look, but don’t remove)
– MSG_WAITALL (don’t give me less than max)
– MSG_DONTROUTE (bypass routing table)
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
Socket Options (TCP)
• TCP_KEEPALIVE
– idle time before close (2 hours, default)
• TCP_MAXRT
– set timeout value
• TCP_NODELAY
– disable Nagle Algorithm
– won’t buffer data for larger chunk, but sends
immediately
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;
Project 3: Online Chess
• 1) Start server
• 2) Client A connects
– Client sends handle
– Server sends color
• 3) Client B connects
– Client sends handle
– Server sends color
• 4) Game starts!
• 5) Server sends turn
• 6) If clients turn
– Client sends move
– Server sends OK/Illegal
• 7) Else
– Server sends opponent
move
• 8) When checkmate
– Server sends winner
• 9) Close
• 10) Server returns to
wait for next game
Server Client

More Related Content

Similar to Introduction to sockets tcp ip protocol.ppt

Similar to Introduction to sockets tcp ip protocol.ppt (20)

Sockets
SocketsSockets
Sockets
 
Socket programming in c
Socket programming in cSocket programming in c
Socket programming in c
 
Sockets
Sockets Sockets
Sockets
 
Basic socket programming
Basic socket programmingBasic socket programming
Basic socket programming
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Np unit2
Np unit2Np unit2
Np unit2
 
Byte Ordering - Unit 2.pptx
Byte Ordering - Unit 2.pptxByte Ordering - Unit 2.pptx
Byte Ordering - Unit 2.pptx
 
Computer network (12)
Computer network (12)Computer network (12)
Computer network (12)
 
Network Sockets
Network SocketsNetwork Sockets
Network Sockets
 
Sockets
Sockets Sockets
Sockets
 
Elementary TCP Sockets
Elementary TCP SocketsElementary TCP Sockets
Elementary TCP Sockets
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
Socket Programming TCP:IP PPT.pdf
Socket Programming TCP:IP PPT.pdfSocket Programming TCP:IP PPT.pdf
Socket Programming TCP:IP PPT.pdf
 
sockets
socketssockets
sockets
 
TCP IP
TCP IPTCP IP
TCP IP
 
Socket System Calls
Socket System CallsSocket System Calls
Socket System Calls
 
Networking.ppt
Networking.pptNetworking.ppt
Networking.ppt
 
computerNetworkSecurity.ppt
computerNetworkSecurity.pptcomputerNetworkSecurity.ppt
computerNetworkSecurity.ppt
 
lab04.pdf
lab04.pdflab04.pdf
lab04.pdf
 
Socket programming-tutorial-sk
Socket programming-tutorial-skSocket programming-tutorial-sk
Socket programming-tutorial-sk
 

Recently uploaded

Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012rehmti665
 
Git and Github workshop GDSC MLRITM
Git and Github  workshop GDSC MLRITMGit and Github  workshop GDSC MLRITM
Git and Github workshop GDSC MLRITMgdsc13
 
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Delivery
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on DeliveryCall Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Delivery
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Deliverybabeytanya
 
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark WebGDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark WebJames Anderson
 
VIP Kolkata Call Girl Salt Lake 👉 8250192130 Available With Room
VIP Kolkata Call Girl Salt Lake 👉 8250192130  Available With RoomVIP Kolkata Call Girl Salt Lake 👉 8250192130  Available With Room
VIP Kolkata Call Girl Salt Lake 👉 8250192130 Available With Roomishabajaj13
 
Low Rate Call Girls Kolkata Avani 🤌 8250192130 🚀 Vip Call Girls Kolkata
Low Rate Call Girls Kolkata Avani 🤌  8250192130 🚀 Vip Call Girls KolkataLow Rate Call Girls Kolkata Avani 🤌  8250192130 🚀 Vip Call Girls Kolkata
Low Rate Call Girls Kolkata Avani 🤌 8250192130 🚀 Vip Call Girls Kolkataanamikaraghav4
 
Networking in the Penumbra presented by Geoff Huston at NZNOG
Networking in the Penumbra presented by Geoff Huston at NZNOGNetworking in the Penumbra presented by Geoff Huston at NZNOG
Networking in the Penumbra presented by Geoff Huston at NZNOGAPNIC
 
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607dollysharma2066
 
AlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with FlowsAlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with FlowsThierry TROUIN ☁
 
VIP Call Girls Pune Madhuri 8617697112 Independent Escort Service Pune
VIP Call Girls Pune Madhuri 8617697112 Independent Escort Service PuneVIP Call Girls Pune Madhuri 8617697112 Independent Escort Service Pune
VIP Call Girls Pune Madhuri 8617697112 Independent Escort Service PuneCall girls in Ahmedabad High profile
 
Russian Call Girls Thane Swara 8617697112 Independent Escort Service Thane
Russian Call Girls Thane Swara 8617697112 Independent Escort Service ThaneRussian Call Girls Thane Swara 8617697112 Independent Escort Service Thane
Russian Call Girls Thane Swara 8617697112 Independent Escort Service ThaneCall girls in Ahmedabad High profile
 
Call Girls in East Of Kailash 9711199171 Delhi Enjoy Call Girls With Our Escorts
Call Girls in East Of Kailash 9711199171 Delhi Enjoy Call Girls With Our EscortsCall Girls in East Of Kailash 9711199171 Delhi Enjoy Call Girls With Our Escorts
Call Girls in East Of Kailash 9711199171 Delhi Enjoy Call Girls With Our Escortsindian call girls near you
 
Denver Web Design brochure for public viewing
Denver Web Design brochure for public viewingDenver Web Design brochure for public viewing
Denver Web Design brochure for public viewingbigorange77
 
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝soniya singh
 

Recently uploaded (20)

Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
 
Model Call Girl in Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in  Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in  Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
 
Git and Github workshop GDSC MLRITM
Git and Github  workshop GDSC MLRITMGit and Github  workshop GDSC MLRITM
Git and Github workshop GDSC MLRITM
 
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Delivery
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on DeliveryCall Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Delivery
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Delivery
 
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark WebGDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
 
VIP Kolkata Call Girl Salt Lake 👉 8250192130 Available With Room
VIP Kolkata Call Girl Salt Lake 👉 8250192130  Available With RoomVIP Kolkata Call Girl Salt Lake 👉 8250192130  Available With Room
VIP Kolkata Call Girl Salt Lake 👉 8250192130 Available With Room
 
Call Girls In South Ex 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICE
Call Girls In South Ex 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICECall Girls In South Ex 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICE
Call Girls In South Ex 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICE
 
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No AdvanceRohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
 
Vip Call Girls Aerocity ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Aerocity ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Aerocity ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Aerocity ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Low Rate Call Girls Kolkata Avani 🤌 8250192130 🚀 Vip Call Girls Kolkata
Low Rate Call Girls Kolkata Avani 🤌  8250192130 🚀 Vip Call Girls KolkataLow Rate Call Girls Kolkata Avani 🤌  8250192130 🚀 Vip Call Girls Kolkata
Low Rate Call Girls Kolkata Avani 🤌 8250192130 🚀 Vip Call Girls Kolkata
 
Rohini Sector 22 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 22 Call Girls Delhi 9999965857 @Sabina Saikh No AdvanceRohini Sector 22 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 22 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
 
Networking in the Penumbra presented by Geoff Huston at NZNOG
Networking in the Penumbra presented by Geoff Huston at NZNOGNetworking in the Penumbra presented by Geoff Huston at NZNOG
Networking in the Penumbra presented by Geoff Huston at NZNOG
 
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No AdvanceRohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
 
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
 
AlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with FlowsAlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with Flows
 
VIP Call Girls Pune Madhuri 8617697112 Independent Escort Service Pune
VIP Call Girls Pune Madhuri 8617697112 Independent Escort Service PuneVIP Call Girls Pune Madhuri 8617697112 Independent Escort Service Pune
VIP Call Girls Pune Madhuri 8617697112 Independent Escort Service Pune
 
Russian Call Girls Thane Swara 8617697112 Independent Escort Service Thane
Russian Call Girls Thane Swara 8617697112 Independent Escort Service ThaneRussian Call Girls Thane Swara 8617697112 Independent Escort Service Thane
Russian Call Girls Thane Swara 8617697112 Independent Escort Service Thane
 
Call Girls in East Of Kailash 9711199171 Delhi Enjoy Call Girls With Our Escorts
Call Girls in East Of Kailash 9711199171 Delhi Enjoy Call Girls With Our EscortsCall Girls in East Of Kailash 9711199171 Delhi Enjoy Call Girls With Our Escorts
Call Girls in East Of Kailash 9711199171 Delhi Enjoy Call Girls With Our Escorts
 
Denver Web Design brochure for public viewing
Denver Web Design brochure for public viewingDenver Web Design brochure for public viewing
Denver Web Design brochure for public viewing
 
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
 

Introduction to sockets tcp ip protocol.ppt

  • 2. Outline • Socket basics • Socket details (TCP and UDP) • Socket options • Final notes
  • 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. Outline • Socket basics •Socket details (TCP and UDP) • Socket options • Final notes
  • 8. Socket Details Outline Unix Network Programming, W. Richard Stevens, 2nd edition, 1998, Prentice Hall • Project 3  Links has samples – C++, Windows and C++, Linux – Java • Code is very similar for Windows • Addresses and Sockets • TCP client-server (talk-tcp, listen-tcp) • UDP client-server (talk-udp, listen-udp) • Misc stuff – setsockopt(), getsockopt() – fcntl()
  • 9. Addresses and Sockets • 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
  • 11. 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
  • 12. 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
  • 13. 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.
  • 14. 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.
  • 15. 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.
  • 16. 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.
  • 17. 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
  • 18. 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.
  • 19. 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); • Same as read() and write() but for flags – MSG_DONTWAIT (this send non-blocking) – MSG_OOB (out of band data, 1 byte sent ahead) – MSG_PEEK (look, but don’t remove) – MSG_WAITALL (don’t give me less than max) – MSG_DONTROUTE (bypass routing table)
  • 20. 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!
  • 21. 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
  • 22. 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)
  • 23. 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
  • 24. 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
  • 25. Socket Options (TCP) • TCP_KEEPALIVE – idle time before close (2 hours, default) • TCP_MAXRT – set timeout value • TCP_NODELAY – disable Nagle Algorithm – won’t buffer data for larger chunk, but sends immediately
  • 26. 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!
  • 27. 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;
  • 28. Project 3: Online Chess • 1) Start server • 2) Client A connects – Client sends handle – Server sends color • 3) Client B connects – Client sends handle – Server sends color • 4) Game starts! • 5) Server sends turn • 6) If clients turn – Client sends move – Server sends OK/Illegal • 7) Else – Server sends opponent move • 8) When checkmate – Server sends winner • 9) Close • 10) Server returns to wait for next game Server Client

Editor's Notes

  1. Length field makes it easier for OS to handle