SlideShare a Scribd company logo
Socket Programming
15-441 Computer Networks, Spring 2008
Xi Liu
Lecture Today
• Motivation for sockets
• What’s in a socket?
• Working with socket
• Concurrent network applications
• Project 1
Why Socket?
• How can I program a network application?
– Share data
– Send messages
– Finish course projects...
• IPC - Interprocess Communication
Network Layering
Application
Presentation
Session
Transport
Network
Data link
Physical
1
2
3
4
5
6
7
Network
Data link
Physical
Application
Presentation
Session
Transport
Network
Data link
Physical
Network Layering
• Why layering?
Application
Presentation
Session
Transport
Network
Data link
Physical
1
2
3
4
5
6
7
Network
Data link
Physical
Application
Presentation
Session
Transport
Network
Data link
Physical
Layering Makes it Easier
• Application programmer
– Doesn’t need to send IP packets
– Doesn’t need to send Ethernet frames
– Doesn’t need to know how TCP implements
reliability
• Only need a way to pass the data down
– Socket is the API to access transport layer
functions
What Lower Layer Need to Know?
• We pass the data down. What else does the
lower layer need to know?
What Lower Layer Need to Know?
• We pass the data down. What else does the
lower layer need to know?
• How to identify the destination process?
– Where to send the data? (Addressing)
– What process gets the data when it is there?
(Multiplexing)
Identify the Destination
Connection socket pair
(128.2.194.242:3479, 208.216.181.15:80)
HTTP Server
(port 80)
Client
Client socket address
128.2.194.242:3479
Server socket address
208.216.181.15:80
Client host address
128.2.194.242
Server host address
208.216.181.15
FTP Server
(port 21)
• Addressing
– IP address
– hostname (resolve to IP address via DNS)
• Multiplexing
– port
Sockets
• How to use sockets
– Setup socket
• Where is the remote machine (IP address, hostname)
• What service gets the data (port)
– Send and Receive
• Designed just like any other I/O in unix
• send -- write
• recv -- read
– Close the socket
Client /
Server
Session
Client Server
socket socket
bind
listen
read
write
read
write
Connection
request
read
close
close
EOF
open_listenfd
accept
connect
open_clientfd
Overview
Step 1 – Setup Socket
• Both client and server need to setup the socket
– int socket(int domain, int type, int protocol);
• domain
– AF_INET -- IPv4 (AF_INET6 for IPv6)
• type
– SOCK_STREAM -- TCP
– SOCK_DGRAM -- UDP
• protocol
– 0
• For example,
– int sockfd = socket(AF_INET, SOCK_STREAM, 0);
Step 2 (Server) - Binding
• Only server need to bind
– int bind(int sockfd, const struct sockaddr *my_addr,
socklen_t addrlen);
• sockfd
– file descriptor socket() returned
• my_addr
– struct sockaddr_in for IPv4
– cast (struct sockaddr_in*) to (struct sockaddr*)
struct sockaddr_in {
short sin_family; // e.g. AF_INET
unsigned short sin_port; // e.g. htons(3490)
struct in_addr sin_addr; // see struct in_addr, below
char sin_zero[8]; // zero this if you want to
};
struct in_addr {
unsigned long s_addr; // load with inet_aton()
};
What is that Cast?
• bind() takes in protocol-independent (struct
sockaddr*)
– C’s polymorphism
– There are structs for IPv6, etc.
struct sockaddr {
unsigned short sa_family; // address family
char sa_data[14]; // protocol address
};
Step 2 (Server) - Binding contd.
• addrlen
– size of the sockaddr_in
struct sockaddr_in saddr;
int sockfd;
unsigned short port = 80;
if((sockfd=socket(AF_INET, SOCK_STREAM, 0) < 0) { // from back a couple slides
printf(“Error creating socketn”);
...
}
memset(&saddr, '0', sizeof(saddr)); // zero structure out
saddr.sin_family = AF_INET; // match the socket() call
saddr.sin_addr.s_addr = htonl(INADDR_ANY); // bind to any local address
saddr.sin_port = htons(port); // specify port to listen on
if((bind(sockfd, (struct sockaddr *) &saddr, sizeof(saddr)) < 0) { // bind!
printf(“Error bindingn”);
...
}
What is htonl(), htons()?
• Byte ordering
– Network order is big-endian
– Host order can be big- or little-endian
• x86 is little-endian
• SPARC is big-endian
• Conversion
– htons(), htonl(): host to network short/long
– ntohs(), ntohl(): network order to host short/long
• What need to be converted?
– Addresses
– Port
– etc.
Step 3 (Server) - Listen
• Now we can listen
– int listen(int sockfd, int backlog);
• sockfd
– again, file descriptor socket() returned
• backlog
– number of pending connections to queue
• For example,
– listen(sockfd, 5);
Step 4 (Server) - Accept
• Server must explicitly accept incoming connections
– int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen)
• sockfd
– again... file descriptor socket() returned
• addr
– pointer to store client address, (struct sockaddr_in *) cast to
(struct sockaddr *)
• addrlen
– pointer to store the returned size of addr, should be
sizeof(*addr)
• For example
– int isock=accept(sockfd, (struct sockaddr_in *) &caddr, &clen);
Put Server Together
struct sockaddr_in saddr, caddr;
int sockfd, clen, isock;
unsigned short port = 80;
if((sockfd=socket(AF_INET, SOCK_STREAM, 0) < 0) { // from back a couple slides
printf(“Error creating socketn”);
...
}
memset(&saddr, '0', sizeof(saddr)); // zero structure out
saddr.sin_family = AF_INET; // match the socket() call
saddr.sin_addr.s_addr = htonl(INADDR_ANY); // bind to any local address
saddr.sin_port = htons(port); // specify port to listen on
if((bind(sockfd, (struct sockaddr *) &saddr, sizeof(saddr)) < 0) { // bind!
printf(“Error bindingn”);
...
}
if(listen(sockfd, 5) < 0) { // listen for incoming connections
printf(“Error listeningn”);
...
}
clen=sizeof(caddr)
if((isock=accept(sockfd, (struct sockaddr *) &caddr, &clen)) < 0) { // accept one
printf(“Error acceptingn”);
...
}
What about client?
• Client need not bind, listen, and accept
• All client need to do is to connect
– int connect(int sockfd, const struct sockaddr
*saddr, socklen_t addrlen);
• For example,
– connect(sockfd, (struct sockaddr *) &saddr,
sizeof(saddr));
Domain Name System (DNS)
• What if I want to send data to “www.slashdot.org”?
– DNS: Conceptually, DNS is a database collection of host entries
• hostname -> IP address
– struct hostent *gethostbyname(const char *name);
• IP address -> hostname
– struct hostent *gethostbyaddr(const char *addr, int len, int
type);
struct hostent {
char *h_name; // official hostname
char **h_aliases; // vector of alternative hostnames
int h_addrtype; // address type, e.g. AF_INET
int h_length; // length of address in bytes, e.g. 4 for IPv4
char **h_addr_list; // vector of addresses
char *h_addr; // first host address, synonym for
h_addr_list[0]
};
Put Client Together
struct sockaddr_in saddr;
struct hostent *h;
int sockfd, connfd;
unsigned short port = 80;
if((sockfd=socket(AF_INET, SOCK_STREAM, 0) < 0) { // from back a couple slides
printf(“Error creating socketn”);
...
}
if((h=gethostbyname(“www.slashdot.org”)) == NULL) { // Lookup the hostname
printf(“Unknown hostn”);
...
}
memset(&saddr, '0', sizeof(saddr)); // zero structure out
saddr.sin_family = AF_INET; // match the socket() call
memcpy((char *) &saddr.sin_addr.s_addr, h->h_addr_list[0], h->h_length); // copy the address
saddr.sin_port = htons(port); // specify port to connect to
if((connfd=connect(sockfd, (struct sockaddr *) &saddr, sizeof(saddr)) < 0) { // connect!
printf(“Cannot connectn”);
...
}
We Are Connected
• Server accepting connections and client
connecting to servers
• Send and receive data
– ssize_t read(int fd, void *buf, size_t len);
– ssize_t write(int fd, const void *buf, size_t len);
• For example,
– read(sockfd, buffer, sizeof(buffer));
– write(sockfd, “heyn”, strlen(“heyn”));
TCP Framing
• TCP does NOT guarantee message boundaries
– IRC commands are terminated by a newline
– But you may not get one at the end of read(), e.g.
• One Send “Hellon”
• Multiple Receives “He”, “llon”
– If you don’t get the entire line from one read(),
use a buffer
Client /
Server
Session
Client Server
socket socket
bind
listen
read
write
read
write
Connection
request
read
close
close
EOF
open_listenfd
accept
connect
open_clientfd
Revisited
Close the Socket
• Don’t forget to close the socket descriptor,
like a file
– int close(int sockfd);
• Now server can loop around and accept a new
connection when the old one finishes
• What’s wrong here?
client 1 server client 2
call connect
call accept
call read
ret connect
ret accept
call connect
call fgets
User goes
out to lunch
Client 1 blocks
waiting for user
to type in data
Client 2 blocks
waiting to complete
its connection
request until after
lunch!
Server blocks
waiting for
data from
Client 1
Taken from D. Murray, R. Bryant, and G. Langale 15-441/213 slides
Server Flaw
Concurrent Servers
client 1 server client 2
call connect
call accept
ret connect
ret accept
call connect
call fgets
User goes
out to lunch
Client 1
blocks
waiting for
user to type
in data
call accept
ret connect
ret accept call fgets
write
write
call read
end read
close
close
call read (don’t block)
call read
Taken from D. Murray, R. Bryant, and G. Langale 15-441/213 slides
Concurrency
• Threading
– Easier to understand
– Race conditions increase complexity
• Select()
– Explicit control flows, no race conditions
– Explicit control more complicated
• There is no clear winner, but you MUST use
select()…
What is select()?
• Monitor multiple descriptors
• How does it work?
– Setup sets of sockets to monitor
– select(): blocking until something happens
– “Something” could be
• Incoming connection: accept()
• Clients sending data: read()
• Pending data to send: write()
• Timeout
Concurrency – Step 1
• Allowing address reuse
• Then we set the sockets to be non-blocking
int sock, opts=1;
sock = socket(...); // To give you an idea of where the new code goes
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opts, sizeof(opts));
if((opts = fcntl(sock, F_GETFL)) < 0) { // Get current options
printf(“Error...n”);
...
}
opts = (opts | O_NONBLOCK); // Don't clobber your old settings
if(fcntl(sock, F_SETFL, opts) < 0) {
printf(“Error...n”);
...
}
bind(...); // To again give you an idea where the new code goes
Concurrency – Step 2
• Monitor sockets with select()
– int select(int maxfd, fd_set *readfds, fd_set *writefds,
fd_set *exceptfds, const struct timespec *timeout);
• maxfd
– max file descriptor + 1
• fd_set: bit vector with FD_SETSIZE bits
– readfds: bit vector of read descriptors to monitor
– writefds: bit vector of write descriptors to monitor
– exceptfds: set to NULL
• timeout
– how long to wait without activity before returning
What about bit vectors?
• void FD_ZERO(fd_set *fdset);
– clear out all bits
• void FD_SET(int fd, fd_set *fdset);
– set one bit
• void FD_CLR(int fd, fd_set *fdset);
– clear one bit
• int FD_ISSET(int fd, fd_set *fdset);
– test whether fd bit is set
The Server
// socket() call and non-blocking code is above this point
if((bind(sockfd, (struct sockaddr *) &saddr, sizeof(saddr)) < 0) { // bind!
printf(“Error bindingn”);
...
}
if(listen(sockfd, 5) < 0) { // listen for incoming connections
printf(“Error listeningn”);
...
}
clen=sizeof(caddr);
// Setup pool.read_set with an FD_ZERO() and FD_SET() for
// your server socket file descriptor. (whatever socket() returned)
while(1) {
pool.ready_set = pool.read_set; // Save the current state
pool.nready = select(pool.maxfd+1, &pool.ready_set, &pool.write_set, NULL, NULL);
if(FD_ISSET(sockfd, &pool.ready_set)) { // Check if there is an incoming conn
isock=accept(sockfd, (struct sockaddr *) &caddr, &clen); // accept it
add_client(isock, &pool); // add the client by the incoming socket fd
}
check_clients(&pool); // check if any data needs to be sent/received from clients
}
...
close(sockfd);
What is pool?
typedef struct { /* represents a pool of connected descriptors */
int maxfd; /* largest descriptor in read_set */
fd_set read_set; /* set of all active read descriptors */
fd_set write_set; /* set of all active read descriptors */
fd_set ready_set; /* subset of descriptors ready for reading */
int nready; /* number of ready descriptors from select */
int maxi; /* highwater index into client array */
int clientfd[FD_SETSIZE]; /* set of active descriptors */
rio_t clientrio[FD_SETSIZE]; /* set of active read buffers */
... // ADD WHAT WOULD BE HELPFUL FOR PROJECT1
} pool;
What about checking clients?
• The main loop only tests for incoming connections
– There are other reasons the server wakes up
– Clients are sending data, pending data to write to
buffer, clients closing connections, etc.
• Store all client file descriptors
– in pool
• Keep the while(1) loop thin
– Delegate to functions
• Come up with your own design
Summary
• Sockets
– socket setup
– I/O
– close
• Client: socket()----------------------->connect()->I/O->close()
• Server: socket()->bind()->listen()->accept()--->I/O->close()
• DNS
– gethostbyname()
• Concurrency
– select()
• Bit vector operations
– fd_set, FD_ZERO(), FD_SET(), FD_CLR(), FD_ISSET()
About Project 1
• Standalone IRC server
– Checkpoint 1: subversion and Makefile
• Check in a Makefile and source code
• Makefile can build executable named sircd
• No server functions necessary
– Checkpoint 2: echo server
• Use select() to handle multiple clients
Suggestions
• Start early!
– Work ahead of checkpoints
• Read the man pages
• Email (xil at cs dot cmu dot edu) if you didn’t
get a svn username and password

More Related Content

Similar to 03-socketprogrsamming forcoleeger students.ppt (20)

PDF
Network Programming Assignment Help
HelpWithAssignment.com
 
PPTX
Socket programming
Anurag Tomar
 
PPTX
L5-Sockets.pptx
ycelgemici1
 
PPT
Net Programming.ppt
EloAcubaOgardo
 
PPT
Network programming-Network for engineering
insdcn
 
PPT
Network Prog.ppt
EloOgardo
 
PPTX
Basics of sockets
AviNash ChaVhan
 
PPT
Sockets in unix
swtjerin4u
 
PPT
03 sockets
Pavan Illa
 
PPT
Basic socket programming
Kristian Arjianto
 
PDF
sockets
AbhinavRapartiwar
 
PPT
LECTURE-17(Socket Programming) Detailed.
qamarmajeed0000
 
PDF
socketProgramming-TCP-and UDP-overview.pdf
Shilpachaudhari10
 
PPT
Socket programming-tutorial-sk
sureshkarthick37
 
PPT
Socket System Calls
Avinash Varma Kalidindi
 
PDF
Socket programming using C
Ajit Nayak
 
PDF
Socket programming
Rajivarnan (Rajiv)
 
PPTX
Socket programming in c
Md. Golam Hossain
 
DOCX
Udp socket programming(Florian)
Flor Ian
 
Network Programming Assignment Help
HelpWithAssignment.com
 
Socket programming
Anurag Tomar
 
L5-Sockets.pptx
ycelgemici1
 
Net Programming.ppt
EloAcubaOgardo
 
Network programming-Network for engineering
insdcn
 
Network Prog.ppt
EloOgardo
 
Basics of sockets
AviNash ChaVhan
 
Sockets in unix
swtjerin4u
 
03 sockets
Pavan Illa
 
Basic socket programming
Kristian Arjianto
 
LECTURE-17(Socket Programming) Detailed.
qamarmajeed0000
 
socketProgramming-TCP-and UDP-overview.pdf
Shilpachaudhari10
 
Socket programming-tutorial-sk
sureshkarthick37
 
Socket System Calls
Avinash Varma Kalidindi
 
Socket programming using C
Ajit Nayak
 
Socket programming
Rajivarnan (Rajiv)
 
Socket programming in c
Md. Golam Hossain
 
Udp socket programming(Florian)
Flor Ian
 

Recently uploaded (20)

PPTX
L1A Season 1 ENGLISH made by A hegy fixed
toszolder91
 
PPTX
INTEGRATION OF ICT IN LEARNING AND INCORPORATIING TECHNOLOGY
kvshardwork1235
 
PPTX
一比一原版(SUNY-Albany毕业证)纽约州立大学奥尔巴尼分校毕业证如何办理
Taqyea
 
PPT
Computer Securityyyyyyyy - Chapter 2.ppt
SolomonSB
 
PDF
Build Fast, Scale Faster: Milvus vs. Zilliz Cloud for Production-Ready AI
Zilliz
 
PPTX
PM200.pptxghjgfhjghjghjghjghjghjghjghjghjghj
breadpaan921
 
PPT
introductio to computers by arthur janry
RamananMuthukrishnan
 
PDF
𝐁𝐔𝐊𝐓𝐈 𝐊𝐄𝐌𝐄𝐍𝐀𝐍𝐆𝐀𝐍 𝐊𝐈𝐏𝐄𝐑𝟒𝐃 𝐇𝐀𝐑𝐈 𝐈𝐍𝐈 𝟐𝟎𝟐𝟓
hokimamad0
 
PPTX
Research Design - Report on seminar in thesis writing. PPTX
arvielobos1
 
PPTX
英国假毕业证诺森比亚大学成绩单GPA修改UNN学生卡网上可查学历成绩单
Taqyea
 
PPTX
L1A Season 1 Guide made by A hegy Eng Grammar fixed
toszolder91
 
PPTX
西班牙武康大学毕业证书{UCAMOfferUCAM成绩单水印}原版制作
Taqyea
 
PPTX
Cost_of_Quality_Presentation_Software_Engineering.pptx
farispalayi
 
PDF
Web Hosting for Shopify WooCommerce etc.
Harry_Phoneix Harry_Phoneix
 
PPTX
sajflsajfljsdfljslfjslfsdfas;fdsfksadfjlsdflkjslgfs;lfjlsajfl;sajfasfd.pptx
theknightme
 
PPTX
unit 2_2 copy right fdrgfdgfai and sm.pptx
nepmithibai2024
 
PPT
introduction to networking with basics coverage
RamananMuthukrishnan
 
PPTX
法国巴黎第二大学本科毕业证{Paris 2学费发票Paris 2成绩单}办理方法
Taqyea
 
PPTX
一比一原版(LaTech毕业证)路易斯安那理工大学毕业证如何办理
Taqyea
 
PDF
Apple_Environmental_Progress_Report_2025.pdf
yiukwong
 
L1A Season 1 ENGLISH made by A hegy fixed
toszolder91
 
INTEGRATION OF ICT IN LEARNING AND INCORPORATIING TECHNOLOGY
kvshardwork1235
 
一比一原版(SUNY-Albany毕业证)纽约州立大学奥尔巴尼分校毕业证如何办理
Taqyea
 
Computer Securityyyyyyyy - Chapter 2.ppt
SolomonSB
 
Build Fast, Scale Faster: Milvus vs. Zilliz Cloud for Production-Ready AI
Zilliz
 
PM200.pptxghjgfhjghjghjghjghjghjghjghjghjghj
breadpaan921
 
introductio to computers by arthur janry
RamananMuthukrishnan
 
𝐁𝐔𝐊𝐓𝐈 𝐊𝐄𝐌𝐄𝐍𝐀𝐍𝐆𝐀𝐍 𝐊𝐈𝐏𝐄𝐑𝟒𝐃 𝐇𝐀𝐑𝐈 𝐈𝐍𝐈 𝟐𝟎𝟐𝟓
hokimamad0
 
Research Design - Report on seminar in thesis writing. PPTX
arvielobos1
 
英国假毕业证诺森比亚大学成绩单GPA修改UNN学生卡网上可查学历成绩单
Taqyea
 
L1A Season 1 Guide made by A hegy Eng Grammar fixed
toszolder91
 
西班牙武康大学毕业证书{UCAMOfferUCAM成绩单水印}原版制作
Taqyea
 
Cost_of_Quality_Presentation_Software_Engineering.pptx
farispalayi
 
Web Hosting for Shopify WooCommerce etc.
Harry_Phoneix Harry_Phoneix
 
sajflsajfljsdfljslfjslfsdfas;fdsfksadfjlsdflkjslgfs;lfjlsajfl;sajfasfd.pptx
theknightme
 
unit 2_2 copy right fdrgfdgfai and sm.pptx
nepmithibai2024
 
introduction to networking with basics coverage
RamananMuthukrishnan
 
法国巴黎第二大学本科毕业证{Paris 2学费发票Paris 2成绩单}办理方法
Taqyea
 
一比一原版(LaTech毕业证)路易斯安那理工大学毕业证如何办理
Taqyea
 
Apple_Environmental_Progress_Report_2025.pdf
yiukwong
 
Ad

03-socketprogrsamming forcoleeger students.ppt

  • 1. Socket Programming 15-441 Computer Networks, Spring 2008 Xi Liu
  • 2. Lecture Today • Motivation for sockets • What’s in a socket? • Working with socket • Concurrent network applications • Project 1
  • 3. Why Socket? • How can I program a network application? – Share data – Send messages – Finish course projects... • IPC - Interprocess Communication
  • 4. Network Layering Application Presentation Session Transport Network Data link Physical 1 2 3 4 5 6 7 Network Data link Physical Application Presentation Session Transport Network Data link Physical
  • 5. Network Layering • Why layering? Application Presentation Session Transport Network Data link Physical 1 2 3 4 5 6 7 Network Data link Physical Application Presentation Session Transport Network Data link Physical
  • 6. Layering Makes it Easier • Application programmer – Doesn’t need to send IP packets – Doesn’t need to send Ethernet frames – Doesn’t need to know how TCP implements reliability • Only need a way to pass the data down – Socket is the API to access transport layer functions
  • 7. What Lower Layer Need to Know? • We pass the data down. What else does the lower layer need to know?
  • 8. What Lower Layer Need to Know? • We pass the data down. What else does the lower layer need to know? • How to identify the destination process? – Where to send the data? (Addressing) – What process gets the data when it is there? (Multiplexing)
  • 9. Identify the Destination Connection socket pair (128.2.194.242:3479, 208.216.181.15:80) HTTP Server (port 80) Client Client socket address 128.2.194.242:3479 Server socket address 208.216.181.15:80 Client host address 128.2.194.242 Server host address 208.216.181.15 FTP Server (port 21) • Addressing – IP address – hostname (resolve to IP address via DNS) • Multiplexing – port
  • 10. Sockets • How to use sockets – Setup socket • Where is the remote machine (IP address, hostname) • What service gets the data (port) – Send and Receive • Designed just like any other I/O in unix • send -- write • recv -- read – Close the socket
  • 11. Client / Server Session Client Server socket socket bind listen read write read write Connection request read close close EOF open_listenfd accept connect open_clientfd Overview
  • 12. Step 1 – Setup Socket • Both client and server need to setup the socket – int socket(int domain, int type, int protocol); • domain – AF_INET -- IPv4 (AF_INET6 for IPv6) • type – SOCK_STREAM -- TCP – SOCK_DGRAM -- UDP • protocol – 0 • For example, – int sockfd = socket(AF_INET, SOCK_STREAM, 0);
  • 13. Step 2 (Server) - Binding • Only server need to bind – int bind(int sockfd, const struct sockaddr *my_addr, socklen_t addrlen); • sockfd – file descriptor socket() returned • my_addr – struct sockaddr_in for IPv4 – cast (struct sockaddr_in*) to (struct sockaddr*) struct sockaddr_in { short sin_family; // e.g. AF_INET unsigned short sin_port; // e.g. htons(3490) struct in_addr sin_addr; // see struct in_addr, below char sin_zero[8]; // zero this if you want to }; struct in_addr { unsigned long s_addr; // load with inet_aton() };
  • 14. What is that Cast? • bind() takes in protocol-independent (struct sockaddr*) – C’s polymorphism – There are structs for IPv6, etc. struct sockaddr { unsigned short sa_family; // address family char sa_data[14]; // protocol address };
  • 15. Step 2 (Server) - Binding contd. • addrlen – size of the sockaddr_in struct sockaddr_in saddr; int sockfd; unsigned short port = 80; if((sockfd=socket(AF_INET, SOCK_STREAM, 0) < 0) { // from back a couple slides printf(“Error creating socketn”); ... } memset(&saddr, '0', sizeof(saddr)); // zero structure out saddr.sin_family = AF_INET; // match the socket() call saddr.sin_addr.s_addr = htonl(INADDR_ANY); // bind to any local address saddr.sin_port = htons(port); // specify port to listen on if((bind(sockfd, (struct sockaddr *) &saddr, sizeof(saddr)) < 0) { // bind! printf(“Error bindingn”); ... }
  • 16. What is htonl(), htons()? • Byte ordering – Network order is big-endian – Host order can be big- or little-endian • x86 is little-endian • SPARC is big-endian • Conversion – htons(), htonl(): host to network short/long – ntohs(), ntohl(): network order to host short/long • What need to be converted? – Addresses – Port – etc.
  • 17. Step 3 (Server) - Listen • Now we can listen – int listen(int sockfd, int backlog); • sockfd – again, file descriptor socket() returned • backlog – number of pending connections to queue • For example, – listen(sockfd, 5);
  • 18. Step 4 (Server) - Accept • Server must explicitly accept incoming connections – int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen) • sockfd – again... file descriptor socket() returned • addr – pointer to store client address, (struct sockaddr_in *) cast to (struct sockaddr *) • addrlen – pointer to store the returned size of addr, should be sizeof(*addr) • For example – int isock=accept(sockfd, (struct sockaddr_in *) &caddr, &clen);
  • 19. Put Server Together struct sockaddr_in saddr, caddr; int sockfd, clen, isock; unsigned short port = 80; if((sockfd=socket(AF_INET, SOCK_STREAM, 0) < 0) { // from back a couple slides printf(“Error creating socketn”); ... } memset(&saddr, '0', sizeof(saddr)); // zero structure out saddr.sin_family = AF_INET; // match the socket() call saddr.sin_addr.s_addr = htonl(INADDR_ANY); // bind to any local address saddr.sin_port = htons(port); // specify port to listen on if((bind(sockfd, (struct sockaddr *) &saddr, sizeof(saddr)) < 0) { // bind! printf(“Error bindingn”); ... } if(listen(sockfd, 5) < 0) { // listen for incoming connections printf(“Error listeningn”); ... } clen=sizeof(caddr) if((isock=accept(sockfd, (struct sockaddr *) &caddr, &clen)) < 0) { // accept one printf(“Error acceptingn”); ... }
  • 20. What about client? • Client need not bind, listen, and accept • All client need to do is to connect – int connect(int sockfd, const struct sockaddr *saddr, socklen_t addrlen); • For example, – connect(sockfd, (struct sockaddr *) &saddr, sizeof(saddr));
  • 21. Domain Name System (DNS) • What if I want to send data to “www.slashdot.org”? – DNS: Conceptually, DNS is a database collection of host entries • hostname -> IP address – struct hostent *gethostbyname(const char *name); • IP address -> hostname – struct hostent *gethostbyaddr(const char *addr, int len, int type); struct hostent { char *h_name; // official hostname char **h_aliases; // vector of alternative hostnames int h_addrtype; // address type, e.g. AF_INET int h_length; // length of address in bytes, e.g. 4 for IPv4 char **h_addr_list; // vector of addresses char *h_addr; // first host address, synonym for h_addr_list[0] };
  • 22. Put Client Together struct sockaddr_in saddr; struct hostent *h; int sockfd, connfd; unsigned short port = 80; if((sockfd=socket(AF_INET, SOCK_STREAM, 0) < 0) { // from back a couple slides printf(“Error creating socketn”); ... } if((h=gethostbyname(“www.slashdot.org”)) == NULL) { // Lookup the hostname printf(“Unknown hostn”); ... } memset(&saddr, '0', sizeof(saddr)); // zero structure out saddr.sin_family = AF_INET; // match the socket() call memcpy((char *) &saddr.sin_addr.s_addr, h->h_addr_list[0], h->h_length); // copy the address saddr.sin_port = htons(port); // specify port to connect to if((connfd=connect(sockfd, (struct sockaddr *) &saddr, sizeof(saddr)) < 0) { // connect! printf(“Cannot connectn”); ... }
  • 23. We Are Connected • Server accepting connections and client connecting to servers • Send and receive data – ssize_t read(int fd, void *buf, size_t len); – ssize_t write(int fd, const void *buf, size_t len); • For example, – read(sockfd, buffer, sizeof(buffer)); – write(sockfd, “heyn”, strlen(“heyn”));
  • 24. TCP Framing • TCP does NOT guarantee message boundaries – IRC commands are terminated by a newline – But you may not get one at the end of read(), e.g. • One Send “Hellon” • Multiple Receives “He”, “llon” – If you don’t get the entire line from one read(), use a buffer
  • 25. Client / Server Session Client Server socket socket bind listen read write read write Connection request read close close EOF open_listenfd accept connect open_clientfd Revisited
  • 26. Close the Socket • Don’t forget to close the socket descriptor, like a file – int close(int sockfd); • Now server can loop around and accept a new connection when the old one finishes • What’s wrong here?
  • 27. client 1 server client 2 call connect call accept call read ret connect ret accept call connect call fgets User goes out to lunch Client 1 blocks waiting for user to type in data Client 2 blocks waiting to complete its connection request until after lunch! Server blocks waiting for data from Client 1 Taken from D. Murray, R. Bryant, and G. Langale 15-441/213 slides Server Flaw
  • 28. Concurrent Servers client 1 server client 2 call connect call accept ret connect ret accept call connect call fgets User goes out to lunch Client 1 blocks waiting for user to type in data call accept ret connect ret accept call fgets write write call read end read close close call read (don’t block) call read Taken from D. Murray, R. Bryant, and G. Langale 15-441/213 slides
  • 29. Concurrency • Threading – Easier to understand – Race conditions increase complexity • Select() – Explicit control flows, no race conditions – Explicit control more complicated • There is no clear winner, but you MUST use select()…
  • 30. What is select()? • Monitor multiple descriptors • How does it work? – Setup sets of sockets to monitor – select(): blocking until something happens – “Something” could be • Incoming connection: accept() • Clients sending data: read() • Pending data to send: write() • Timeout
  • 31. Concurrency – Step 1 • Allowing address reuse • Then we set the sockets to be non-blocking int sock, opts=1; sock = socket(...); // To give you an idea of where the new code goes setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opts, sizeof(opts)); if((opts = fcntl(sock, F_GETFL)) < 0) { // Get current options printf(“Error...n”); ... } opts = (opts | O_NONBLOCK); // Don't clobber your old settings if(fcntl(sock, F_SETFL, opts) < 0) { printf(“Error...n”); ... } bind(...); // To again give you an idea where the new code goes
  • 32. Concurrency – Step 2 • Monitor sockets with select() – int select(int maxfd, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, const struct timespec *timeout); • maxfd – max file descriptor + 1 • fd_set: bit vector with FD_SETSIZE bits – readfds: bit vector of read descriptors to monitor – writefds: bit vector of write descriptors to monitor – exceptfds: set to NULL • timeout – how long to wait without activity before returning
  • 33. What about bit vectors? • void FD_ZERO(fd_set *fdset); – clear out all bits • void FD_SET(int fd, fd_set *fdset); – set one bit • void FD_CLR(int fd, fd_set *fdset); – clear one bit • int FD_ISSET(int fd, fd_set *fdset); – test whether fd bit is set
  • 34. The Server // socket() call and non-blocking code is above this point if((bind(sockfd, (struct sockaddr *) &saddr, sizeof(saddr)) < 0) { // bind! printf(“Error bindingn”); ... } if(listen(sockfd, 5) < 0) { // listen for incoming connections printf(“Error listeningn”); ... } clen=sizeof(caddr); // Setup pool.read_set with an FD_ZERO() and FD_SET() for // your server socket file descriptor. (whatever socket() returned) while(1) { pool.ready_set = pool.read_set; // Save the current state pool.nready = select(pool.maxfd+1, &pool.ready_set, &pool.write_set, NULL, NULL); if(FD_ISSET(sockfd, &pool.ready_set)) { // Check if there is an incoming conn isock=accept(sockfd, (struct sockaddr *) &caddr, &clen); // accept it add_client(isock, &pool); // add the client by the incoming socket fd } check_clients(&pool); // check if any data needs to be sent/received from clients } ... close(sockfd);
  • 35. What is pool? typedef struct { /* represents a pool of connected descriptors */ int maxfd; /* largest descriptor in read_set */ fd_set read_set; /* set of all active read descriptors */ fd_set write_set; /* set of all active read descriptors */ fd_set ready_set; /* subset of descriptors ready for reading */ int nready; /* number of ready descriptors from select */ int maxi; /* highwater index into client array */ int clientfd[FD_SETSIZE]; /* set of active descriptors */ rio_t clientrio[FD_SETSIZE]; /* set of active read buffers */ ... // ADD WHAT WOULD BE HELPFUL FOR PROJECT1 } pool;
  • 36. What about checking clients? • The main loop only tests for incoming connections – There are other reasons the server wakes up – Clients are sending data, pending data to write to buffer, clients closing connections, etc. • Store all client file descriptors – in pool • Keep the while(1) loop thin – Delegate to functions • Come up with your own design
  • 37. Summary • Sockets – socket setup – I/O – close • Client: socket()----------------------->connect()->I/O->close() • Server: socket()->bind()->listen()->accept()--->I/O->close() • DNS – gethostbyname() • Concurrency – select() • Bit vector operations – fd_set, FD_ZERO(), FD_SET(), FD_CLR(), FD_ISSET()
  • 38. About Project 1 • Standalone IRC server – Checkpoint 1: subversion and Makefile • Check in a Makefile and source code • Makefile can build executable named sircd • No server functions necessary – Checkpoint 2: echo server • Use select() to handle multiple clients
  • 39. Suggestions • Start early! – Work ahead of checkpoints • Read the man pages • Email (xil at cs dot cmu dot edu) if you didn’t get a svn username and password