Académique Documents
Professionnel Documents
Culture Documents
Application
Network API
Protocol A
Protocol B
Protocol C
Socket
A socket is an abstract representation of a
communication endpoint
Sockets work with Unix I/O services just like
files, pipes & FIFOs
Sockets needs to
establishing a connection
specifying communication endpoint addresses
3
Creating a Socket
int socket(int family, int type,
int proto);
family specifies the protocol family
PF_INET for TCP/IP
socket()
The socket() system call returns a socket
descriptor (small integer) or -1 on error
socket() allocates resources needed for a
communication endpoint
but it does not deal with endpoint addressing
sockaddr
sockaddr_in6
length
AF_INET6
port
sockaddr
sa_len
sa_family
sockaddr_in
length
AF_INET
port
addr
Flow-label
sa_data
addr
zero
Scope ID
variable
16 bytes
28 bytes
7
uint16_t
uint16_t
uint32_t
uint32_t
htons(uint16_t);
ntohs(uint_16_t);
htonl(uint32_t);
ntohl(uint32_t);
10
TCP/IP Addresses
We dont need to deal with sockaddr
structures since we will only deal with a real
protocol family.
bind() Example
int mysock,err;
struct sockaddr_in myaddr;
mysock =
socket(PF_INET,SOCK_STREAM,0);
myaddr.sin_family = AF_INET;
myaddr.sin_port = htons( portnum );
myaddr.sin_addr = htonl( ipaddress);
err=bind(mysock, (sockaddr *)
&myaddr, sizeof(myaddr));
13
14
What is my IP address ?
How can you find out what your IP address is
so you can tell bind() ?
There is no realistic way for you to know the
right IP address to give bind()
what if the computer has multiple network
interfaces?
16
Connection-oriented (TCP)
connect()
listen()
accept()
Connectionless (UDP)
send()
recv()
18
Lecture 11
slides
modified
from
Dave
Hollinger
slides
are are
modified
from
Dave
Hollinger
send/receive data
Terminating a connection
20
21
listen()
int listen(int sockfd, int backlog);
26
accept()
int accept( int sockfd,
struct sockaddr* cliaddr,
socklen_t *addrlen);
27
Client Code
TCP clients can call connect() which:
takes care of establishing an endpoint address for
the client socket
Attempts to establish a connection to the
specified server
3-way handshake
connect()
int connect( int sockfd,
const struct sockaddr *server,
socklen_t addrlen);
33
34
UDP Sockets
Sending data
Receiving data
Connected Mode
36
int sock;
sock = socket(PF_INET, SOCK_DGRAM, 0);
if (sock<0) { /* ERROR */ }
37
sendto()
The return value of sendto() indicates how
much data was accepted by the O.S. for
sending as a datagram
not how much data made it to the destination.
recvfrom()
If buff is not large enough, any extra data is
lost forever...
You can receive 0 bytes of data!
The sockaddr at from is filled in with the
address of the sender
42
More recvfrom()
recvfrom doesnt return until there is a
datagram available,
unless you do something special
46