Lecture 2
Lecture 2
Lecture 2
TCP Programming API
#include <sys/socket.h>
Client + Server :
int socket (int family, int type, int protocol);
Client:
int connect (int sfd, const struct sockaddr *servaddr, socklen_t addrlen);
Server:
int bind(int sfd, const struct sockaddr *servaddr, socklen_t addrlen);
int listen(int sockfd, int backlog);
int accept(int sockfd, struct sockaddr *cliaddr, socklen_t *addrlen);
Client + Server:
#include <unistd.h>
int close(int sockfd);
Socket Addresses - Generic
struct sockaddr {
uint8_t sa_len;
sa_family_t sa_family; /* address family: AF_xxx value */
char sa_data[14];
};
sa_data is a: (like when using unions)
struct sockaddr_in {
uint8_t sin_len; /* length of structure (16)*/
sa_family_t sin_family; /* AF_INET*/
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]; /* not used but always set to zero - remaining to 14*/
};
struct in_addr{
in_addr_t s_addr; /*32 bit IPv4 network byte ordered address*/
};
TCP Programming API
Once a connection is setup:
#include <sys/socket.h>
ssize_t send(int sockfd, const void *buf, size_t nbytes, int flags);
int write(int sockfd, …..) – works as well
ssize_t recv(int sockfd, void *buf, size_t nbytes, int flags);
int read(int sockfd,……) – works as well
TCP Programming
Example – fork
Little Endian/Big endian
In memory data representation
exp mantisa
Float = (sign?-1:1) * 2^exp *1.<mantisa>
Double - 8 bytes
1. Blocking I/O
2. Nonblocking I/O
3. I/O multiplexing (select and poll)
4. Signal driven I/O (SIGIO)
5. Asynchronous I/O (the POSIX
aio_functions)
Network operation steps - READ
1. Waiting for the data to be ready – i.e.
data arrives from the network
2. Copying the data from the kernel to
the process – i.e. copying the data
from the kernel buffer into the
application space.
Blocking I/O Model
Process is
sleeping !
Non-Blocking I/O Model
Process is
active !
Multiplexed I/O Model
Write(…) Write(…)
Write(…) ? Read(…)
Read(…) Write(…)
Read(…) Read(…)
Write(…) ? Read(…)
Read(…) Write(…)
The select system call
#include <sys/select.h>
#include <sys/time.h>
int select(int maxfd+1, fd_set *readset, fd_set *writeset, fd_set *exceptset,
const struct timeval *timeout);
Returns:
positive count of ready descriptors
0 if timeout
-1 on error
memset(&addr, 0, sizeof(addr));
ret = (local_or_remote==true?getsockname(s,(struct sockaddr *)&addr,
(socklen_t*)&addrlen):
getpeername(s,(struct sockaddr *)&addr, (socklen_t*)&addrlen) );
if (ret < 0)
perror("getsock(peer)name");
return addr;
}
MultiClient Chat Server -3
char * getIPAddress(int s, bool local_or_remote) {
struct sockaddr_in addr;
addr = getSocketName(s, local_or_remote);
return inet_ntoa(addr.sin_addr);
}