Introduction To Network Programming Using C/C++
Introduction To Network Programming Using C/C++
Introduction To Network Programming Using C/C++
NETWORKING LABORATORY
Introduction to Network
Programming using C/C++
Slides mostly prepared by Joerg Ott (TKK) and Olaf Bergmann (Uni Bremen TZI)
© 2007 Jegadish. D 1
HELSINKI UNIVERSITY OF TECHNOLOGY
NETWORKING LABORATORY
© 2007 Jegadish. D 2
HELSINKI UNIVERSITY OF TECHNOLOGY
NETWORKING LABORATORY
© 2007 Jegadish. D 3
HELSINKI UNIVERSITY OF TECHNOLOGY
NETWORKING LABORATORY
Address Structures
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];
};
struct in_addr {
in_addr_t s_addr; /* 32-bit IPv4 address */
};
struct sockaddr {
uint8_t sa_len;
sa_family_t sa_family; /* address family: AF_xxx value */
char sa_data[14]; /* protocol-specific address */
};
© 2007 Jegadish. D 4
HELSINKI UNIVERSITY OF TECHNOLOGY
NETWORKING LABORATORY
struct hostent {
char *h_name; // Official name of the host
char **h_aliases; // Alternative names
int h_addrtype; // Address Type (AF_INET)
int h_length; // Length of each address
char **h_addr_list; // Address List
char *h_addr; // h_addr_list[0]
};
© 2007 Jegadish. D 5
HELSINKI UNIVERSITY OF TECHNOLOGY
NETWORKING LABORATORY
© 2007 Jegadish. D 6
HELSINKI UNIVERSITY OF TECHNOLOGY
NETWORKING LABORATORY
© 2007 Jegadish. D 7
HELSINKI UNIVERSITY OF TECHNOLOGY
NETWORKING LABORATORY
Socket Types
Socket Descriptor: similar to file i/o or stdin/stdout
Each socket descriptor represents a connection or a particular IP
and Port address
© 2007 Jegadish. D 8
HELSINKI UNIVERSITY OF TECHNOLOGY
NETWORKING LABORATORY
Socket Creation
int socket(domain,type,proto)
int bind(sd,addr,addrlen)
int createSocket(const sockaddr_in &addr)
Socke t domain
{
AF_INET, PF_INET6
int sd=socket(AF_INET,SOCK_DGRAM,0); Socke t type
if (sd<0) return -1; SOCK_STREAM, SOCK_DGRAM, …
Protocol
0 (a ny), 6 (tcp), 17 (udp)
int yes = 1;
setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, (char*)&yes, sizeof yes);
fcntl(sd,F_SETFL,O_NONBLOCK);
if (bind(sd,(struct sockaddr *)(&addr),sizeof(struct sockaddr))<0) {
std::cerr << strerror(errno) << std::endl;
return -1;
}
return sd;
}
© 2007 Jegadish. D 9
HELSINKI UNIVERSITY OF TECHNOLOGY
NETWORKING LABORATORY
© 2007 Jegadish. D 10
HELSINKI UNIVERSITY OF TECHNOLOGY
NETWORKING LABORATORY
➔ Closing a connection
shutdown (int sd, int mode)
0: no further sending, 1: no further reception, 2: neither sending nor receiving
close(sd) to clean up – beware of data loss!
© 2007 Jegadish. D 11
HELSINKI UNIVERSITY OF TECHNOLOGY
NETWORKING LABORATORY
Sending Data
Connection-oriented (TCP)
write (int sd, char *buffer, size_t length);
writev (int sd, struct iovec *vector, int count);
List of buffers, each with pointer to memory and length
send (int sd, char *buffer, size_t length, int flags)
Connectionless (UDP)
sendto (int sd, char *buffer, size_t length, int flags,
struct sockaddr *target, socklen_t addrlen)
sendmsg (int sd, struct msghdr *msg, int flags)
Target address
Pointer to the memory containing the data
Control information
© 2007 Jegadish. D 12
HELSINKI UNIVERSITY OF TECHNOLOGY
NETWORKING LABORATORY
Receiving Data
Connection-oriented (TCP)
read (int sd, char *buffer, size_t length);
readv (int sd, struct iovec *vector, int count);
List of buffers, each with pointer to memory and length
recv (int sd, char *buffer, size_t length, int flags)
Connectionless (UDP)
recvfrom (int sd, char *buffer, size_t length, int flags,
struct sockaddr *target, socklen_t addrlen)
recvmsg (int sd, struct msghdr *msg, int flags)
Sender address
Pointer to the data
Control information
© 2007 Jegadish. D 13
HELSINKI UNIVERSITY OF TECHNOLOGY
NETWORKING LABORATORY
Further Functions
getpeername (int sd, struct sockaddr *peer, size_t *len)
Obtain the address of the communicating peer
getsockname (int sd, struct sockaddr *local, size_t *len)
Obtain the address of the local socket (e.g., if dynamically assigned)
© 2007 Jegadish. D 14
HELSINKI UNIVERSITY OF TECHNOLOGY
NETWORKING LABORATORY
Multicast reception
➔ Multicast JOIN
setsockopt (sd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
struct ip_mreq *mreq, sizeof (ip_mreq));
struct ip_mreq {
struct in_addr imr_multiaddr; /* IP multicast address of
group */
struct in_addr imr_interface; /* local IP address of
interface */
};
➔ Multicast-LEAVE
setsockopt (sd, IPPROTO_IP, IP_DROP_MEMBERSHIP, struct
ip_mreq *mreq, sizeof (ip_mreq));
© 2007 Jegadish. D 15
HELSINKI UNIVERSITY OF TECHNOLOGY
NETWORKING LABORATORY
© 2007 Jegadish. D 16
HELSINKI UNIVERSITY OF TECHNOLOGY
NETWORKING LABORATORY
© 2007 Jegadish. D 17
HELSINKI UNIVERSITY OF TECHNOLOGY
NETWORKING LABORATORY
Select() example
•
© 2007 Jegadish. D 18
HELSINKI UNIVERSITY OF TECHNOLOGY
NETWORKING LABORATORY
struct pollfd {
int fd; // file descriptor
int events; // events to watch for
int revents; // occurred events
};
Poll events:
POLLIN input pending
POLLOUT socket writable (only needed with non-blocking i/o)
POLLHUP, POLLERR
Timeout is specified in milliseconds
-1 == no timeout, 0 == return immediately (perform real polling)
Handling otherwise identical to select()
© 2007 Jegadish. D 19
HELSINKI UNIVERSITY OF TECHNOLOGY
NETWORKING LABORATORY
Timeouts
Protocols use many timeouts
Some Examples of timeouts are, (i)timeouts used for packet pacing,
(ii)retransmission timeouts
An occurrence of an event may change(set/reset/cancel) the timeout variables
Must be implemented efficiently
select () and poll () allow you to specify a timeout value
In poll(), timeout is specified in milliseconds
and select () provides microseconds resolution (uses struct timeval)
Keep an ordered list of all your timeouts
Store absolute time for the timeout
Event this timeout is about (a timeout event may trigger a change in STATE of the
protocol)
Before calling select/poll
Determine current time (gettimeofday ())
Determine first timeout in list and calculate delta
(if timeout has already passed initiate handling right away)
Parameterize poll/select() with the delta
© 2007 Jegadish. D 20
HELSINKI UNIVERSITY OF TECHNOLOGY
NETWORKING LABORATORY
Timeouts ...contd
struct timeval tv, delta, now;
Example:
/* some event occurs -> calculate absolute time in tv */
Timeout 200ms gettimeofday (&tv, NULL);
tv.tv_usec += 200*1000;
if (tv.tv_usec >= 1000000) {
tv.tv_usec -= 1000000;
tv.tv_sec++;
}
© 2007 Jegadish. D 21
HELSINKI UNIVERSITY OF TECHNOLOGY
NETWORKING LABORATORY
Packet pacing
To achieve a target bit rate, need to send packets in regular
intervals
Calculate your target packet interval from the packet size…
Your own header + 8 bytes UDP + 20 bytes IPv4 + 1024 bytes payload
…and the target bit rate on the command line
© 2007 Jegadish. D 22
HELSINKI UNIVERSITY OF TECHNOLOGY
NETWORKING LABORATORY
© 2007 Jegadish. D 23
HELSINKI UNIVERSITY OF TECHNOLOGY
NETWORKING LABORATORY
Beware of threads
If your coding language allows you to avoid them
Will save you hassle (and overhead) in synchronizing access to internal
data structures
Instead
Maintain your own state explicitly in some data structure
Remember what to do next
E.g., send data at a certain time, wait for a response, etc.
“Register” all socket descriptors for your mainloop
“Register” all your timeouts
Process incoming events for all contexts one by one
© 2007 Jegadish. D 24
HELSINKI UNIVERSITY OF TECHNOLOGY
NETWORKING LABORATORY
Hints (1)
Transport address(es) to receive data on
socket (SOCK_DGRAM, AF_INET, …)
Create and bind an individual UDP socket for every address
Remember host vs. network byte order
© 2007 Jegadish. D 25
HELSINKI UNIVERSITY OF TECHNOLOGY
NETWORKING LABORATORY
Hints (2)
Timer handling
gettimeofday(2) yield detailed system clock reading as (sec, usec) pair
If you work with timeout, calculate its absolute time
In the mainloop, determine the time to wait based upon the current time
This result is what you feed into poll() or select()
Note that both use completely different time formats
If poll()/select() returns 0, a timeout has occurred
© 2007 Jegadish. D 26
HELSINKI UNIVERSITY OF TECHNOLOGY
NETWORKING LABORATORY
Hints (3)
Signals
You may need to catch at least SIGINT: signal (SIGINT, signalhandler);
In this case, you would just set a global variable and return (terminate = 1;)
Need to check the variable regularly even if no packets arrive
Will cause interrupted system calls (errno == EINTR)
Need to check for this also in your main loop and behave accordingly
File access
Regular i/o operation (open/close/read/write, fopen/fclose/fread/fwrite)
MS Windows: you may need O_BINARY to avoid end of line conversion
Use fstat () to obtain file attributes (including file size)
© 2007 Jegadish. D 27