NP 2
NP 2
org
Network Programming – MC 9241
Socket
It is an abstraction that is provided to an application programmer to send or receive data to
another process. Data can be sent to or received from another process running on the same
machine or a different machine.
1 CCET
www.anuupdates.org
Network Programming – MC 9241
UDP sockets
• UDP is packet-oriented
• Info sent in packet format as needed by app.
• Every packet requires address information.
• Lightweight, no connection required.
• Overhead of adding destination address with each packet.
Introduction to Sockets
App
r
r
3 2
r 1
socket Dest.
2 CCET
www.anuupdates.org
Network Programming – MC 9241
SOCK_DGRAM
a.k.a. UDP
unreliable delivery
no order guarantees
no notion of “connection” – app indicates dest. for each packet
can send or receive
App D1
3 2
1
socket D2
D3
Socket functions like connect(), accept(), and bind() require the use of specifically defined address
structures to hold IP address information, port number, and protocol type. This can be one of the
more confusing aspects of socket programming so it is necessary to clearly understand how to use
3 CCET
www.anuupdates.org
Network Programming – MC 9241
the socket address structures. The difficulty is that you can use sockets to program network
applications using different protocols.
For example, we can use IP4, IP6, Unix local, etc. Here is the problem: Each different protocol uses a
different address structure to hold its addressing information, yet they all use the same functions
connect(), accept(), bind() etc. So how do we pass these different structures to a given socket
function that requires an address structure? Well it may not be the way you would think it should
be done and this is because sockets where developed a long time ago before things like a void
pointer where features in C. So this is how it is done:
There is a generic address structure: struct sockaddr. This is the address structure which must be
passed to all of the socket functions requiring an address structure.
This means that you must type cast your specific protocol dependent address structure to the
generic address structure when passing it to these socket functions. Protocol specific address
structures usually start with sockaddr_ and end with a suffix depending on that protocol. For
example:
For example:
struct sockaddr_in myAddressStruct;
//Fill in the address information into myAddressStruct here, (will be explained in detail shortly)
connect(socket_file_descriptor, (struct sockaddr *) &myAddressStruct, sizeof(myAddressStruct));
4 CCET
www.anuupdates.org
Network Programming – MC 9241
For the sa_family variable sin_family always use the constant: PF_INET or AF_INET ***Always
initialize address structures with bzero() or memset() before filling them in *** ***Make sure you
use the byte ordering functions when necessary for the port and IP address variables otherwise
there will be strange things a happening to your packets*** To convert a string dotted decimal IP4
address to a NETWORK BYTE ORDERED 32 bit value use the functions:
• inet_addr()
• inet_aton()
To convert a 32 bit NETWORK BYTE ORDERED to a IP4 dotted decimal string use: • inet_ntoa()
Same code would have worked regardless of endian-ness of the two machines
gethostbyname Function
gethostbyaddr Function
gethostname Function
getservbyname and getservbyport Functions
1.gethostbyname Function
#include <netdb.h>
struct hostent *gethostbyname (const char *hostname);
Returns: non-null pointer if OK, NULL on error with h_errno set
struct hostent {
5 CCET
www.anuupdates.org
Network Programming – MC 9241
gethostbyaddr Function
• Takes a binary IPv4 address and tries to find the hostname corresponding to that address
• Performs a query for a PTR record
#include <netdb.h>
struct hostent *gethostbyaddr(const char *addr, socklen_t len, int family);
6 CCET
www.anuupdates.org
Network Programming – MC 9241
gethostname Function
• Obtains the host name
#include <unistd.h>
int gethostname(char *name, size_t len);
// On success, zero is returned. On error, -1 is returned, and errno is set appropriately
• Example
#define MAXHOSTNAME 80
char ThisHost[80];
gethostname (ThisHost, MAXHOSTNAME);
#include <netdb.h>
struct servent *getservbyname(const char *servname, const char *protoname);
//returns non-null pointer if OK, NULL on error
struct servent *getservbyport(int port, const char *protoname);
//returns non-null pointer is OK, NULL on error
//port value must by in network byte order
struct servent {
char *s_name; /* official service name */
char **s_ aliases;/* aliases list*/
int s_port;/* port number, network byte order */
char *s_proto;/* protocol to use */
};
7 CCET
www.anuupdates.org
Network Programming – MC 9241
● To perform network I/O, first thing a process must do is call the socket function
● #include <sys/socket.h>
8 CCET
www.anuupdates.org
Network Programming – MC 9241
● The connect function is used by a TCP client to establish a connection with a TCP server:
#include <sys/socket.h>
int connect(int sockfd, const struct sockaddr *servaddr, socklen_t addrlen);
– Returns: 0 if ok, -1 on error
– Sockfd is a socket descriptor returned by the socket function
– 2nd & 3rd args are the socket address structures, must contain the address of
the server to communicate with
– The client does not have to call bind
● The kernel chooses both an ephemeral port and the source IP address
if necessary.
9 CCET
www.anuupdates.org
Network Programming – MC 9241
Bind function
● The bind funtion assigns a local protocol address to a socket.
With IP, combination of 32-bit (IPv4 or 128-bit for IPv6) address, along with a 16-bit TCP
or UDP port number.
#include <sys/socket.h>
int bind(int sockfd, const struct sockaddr *myaddr, socklen_t addrlen);
– Servers bind to their well-known port when they start
– A process can bind a specific IP address to its socket
– Normally, however, a client does not bind an IP address, so that client can
then respond on any interface available on the host.
Listen function
● The listen function is called only by a TCP server and it performs 2 actions
1. Converts an unconnected (active) socket into a passive socket (indicates
kernel should accept incoming connect requests directed to this socket
2. 2nd argument specifies the maximum number of connections kernel should
queue for this socket
● #include <sys/socket.h>
Listen function
● Normally called after both the socket and bind function, only by the server of course
● Backlog - for a given listening socket, the kernel maintains 2 queues:
1. An incomplete connection queue, which contains an entry for each SYN that
has arrived from a client for which server is awaiting completion of the TCP
3-way handshake
2. A completed connection queue, entry for each client with whom 3-way
handshake has completed.
Accept function
10 CCET
www.anuupdates.org
Network Programming – MC 9241
● Accept is called by a TCP server to return the next completed connection from the
front of the completed connection queue.
– If completed queue is empty, the process is put to sleep.
#include <sys/socket.h>
int accept(int sockfd, struct sockaddr *cliaddr, socklen_t *addrlen);
– Returns: non-negative descriptor if OK, -1 on error
– The cliaddr and addrlen args are used to return the protocol address of the
connect peer process (the client).
Exec function
● Only way in which an executable program file on disk can be executed in Unix is for
an existing process to call one of the 6 exec functions
Close function
● Close() function used to close a socket and terminate a TCP connection
#include <unistd.h>
int close(int sockfd);
– Returns: 0 if ok, -1 on error
– Default action of close with a TCP socket description is to mark the socket as
closed and return to the process immediately.
11 CCET
www.anuupdates.org
Network Programming – MC 9241
Iterative Server
Concurrent Server
Slave 1. Receive a speci_c request upon creation as well as access to the socket
Slave 2. Form a reply according to the application protocol and send it back to the client using send
to
Slave 3. Exit _ cost of process/thread creation for each client request
_ while using threads, use thread-safe functions and be careful while passing arguments to threads
12 CCET
www.anuupdates.org
Network Programming – MC 9241
Slave 1. Receive a connection request (i.e., socket for connection) upon creation
Slave 2. Interact with the client using the connection: read request(s) and send back response(s)
Slave 3. Close the connection and exit _ processes created using fork; can also use execve
13 CCET