Socket Prog 4

Embed Size (px)

Citation preview

  • 8/2/2019 Socket Prog 4

    1/33

    Socket ProgrammingPrepared by Rekha Kak

  • 8/2/2019 Socket Prog 4

    2/33

    What is a socket:A socket is a communication mechanism thatallows client/server systems to be developed either locally on a

    single machine, or across network.

    Unix functions such as printing and n/w utilities such as rlogin

    and ftp usually use sockets to communicate. Sockets is a Way to

    speak to other programs using standard Unix file descriptors.

    When Unix programs do any sort of I/O, they do it by reading or

    writing to a file descriptor. A file descriptor is simply aninteger associated with an open file and everything in Unix is a

    file. So when you want to communicate with another program

    over the Internet youre going do it through a file descriptorwhich is a resource assigned to the server process and that process

    alone.

  • 8/2/2019 Socket Prog 4

    3/33

    Where do I get this file descriptor for network

    communication

    We make a call to the socket( )system routine. It returns thesocket descriptor, and we can communicate through it using the

    specialized send( )and recv( ) socket calls.

    Just we can use the normal read()andwrite()calls tocommunicate.

  • 8/2/2019 Socket Prog 4

    4/33

    There are all kinds of sockets.

    1) ARPA Internet addresses (Internet Sockets) AF_INET

    2) Path names on a local node (Unix Sockets) AF_UNIX

    3) CCITT X.25 addresses (X.25 Sockets)

    4) AF_NS Xerox network system sockets

    5) AF_IPX Novell IPX sockets

    6) AF_APPLETALK Appletalk sockets

  • 8/2/2019 Socket Prog 4

    5/33

    Two Types of Internet Sockets

    1.Stream Sockets (SOCK_STREAM)

    2.Datagram Sockets (SOCK_DGRAM)

    Datagram sockets are sometimes called

    connectionless sockets ".

    Implemented in the AF_INET domain by UDP/IPconnections & provide an unsequenced,unreliable service.

    Stream sockets are reliable two-way connectedcommunication streams. They will also be errorfree.

  • 8/2/2019 Socket Prog 4

    6/33

    Telnet application uses stream sockets.

    All the characters you type need to arrive in the same order

    you type them.

    Web browsers use the HTTP protocol which uses streamsockets to get pages.

    How do stream sockets achieve this high level of datatransmission quality?

    They use a protocol called "The Transmission Control

    Protocol", "TCP" .TCP makes sure your data arrives

    sequentially and error-free.

    Datagram sockets :-Why are they called connectionless?

    Why are they unreliable?

    If ou send a data ram it ma arrive. It ma arrive out of

  • 8/2/2019 Socket Prog 4

    7/33

    ,TCP; they use the "UDP

    Why are they connectionless?We dont have to maintainan open connection as we do with stream sockets. You just

    build a packet, attach an IP header on it with destination

    information, and send it out. No connection needed. They are

    generally used for packet-by-packet transfers of

    information. Sample applications: tftp etc.

    How do these programs even work if datagrams

    might get lost?Each application has its own protocol on

    top of UDP. For example, the tftp protocol says that for each

    packet that gets sent, the recipient has to send back a packetthat says, "I got it!" (an "ACK" packet.) If the sender of the

    original packet gets no reply in, say, five seconds, hell re-

    transmit the packet until he finally gets an ACK. This

    acknowledgment procedure is very important whenim lementin SOCK DGRAMa lications.

  • 8/2/2019 Socket Prog 4

    8/33

    SOCK_DAGRAM PACKETS ARE BUILT:

    Data Encapsulation:When a packet is made, the packet is

    wrapped ("encapsulated") in a header (and rarely a footer) bythe first protocol (say, the TFTP protocol), then the whole thing

    (TFTP header included) is encapsulated again by the next

    protocol (say, UDP), then again by the next (IP), then again by the

    final protocol on the hardware (physical layer) (say, Ethernet).

    When another computer receives the packet, the hardware stripsthe Ethernet header, the kernel strips the IP and UDP headers,

    the TFTP program strips the TFTP header, and it finally has the

    data. You can write sockets programs that are exactly the same

    without caring how the data is physically transmitted (serial, thinEthernet, whatever) because programs on lower levels deal with

    it . The actual network,hardware and topology is

    transparent to the socket programmer.

  • 8/2/2019 Socket Prog 4

    9/33

  • 8/2/2019 Socket Prog 4

    10/33

    A layered model more consistent with Unix might be:

    Application Layer (telnet, ftp, etc.)

    Host-to-Host Transport Layer (TCP, UDP)

    Internet Layer (IP and routing)

    Network Access Layer (Ethernet, ATM, or whatever)

    Physical layer (hardware)

  • 8/2/2019 Socket Prog 4

    11/33

    We can see how these layers correspond to the

    encapsulation of the original data.

    All you have to do for stream sockets is send() thedata out. All you have to do for datagram sockets is

    encapsulate the packet in the method of your choice

    and use sendto() sendit out. The kernelbuilds the Transport Layer and Internet Layer on

    for you and the hardware does the Network Access

    Layer.

  • 8/2/2019 Socket Prog 4

    12/33

    Structures and Data HandlingVarious data types used by the sockets interface.

    A socket descriptor. A socket descriptor is of:Int (Just a regular int).

    struct sockaddr. This structure holds socketaddress information for many types of sockets:

    struct sockaddr {

    unsigned short sun_family; //address family, AF_UNIX

    char sun_path[14]; //

    pathname

    };e.g AF_UNIX-> UNIX INTERNAL

    AF_INET-> ARPA INTERNET PROTOCOLS

    AF_ISO -> ISO STANDARD PROTOCOLS

    AF_NS-> XEROX NETWORK SYSTEM

  • 8/2/2019 Socket Prog 4

    13/33

    In the AF_INET domain

    struct sockaddr_in ("in" for"Internet".)

    struct sockaddr_in {short int sin_family; // Addressfamily e.g AF_INET

    unsigned short int sin_port; // Port

    number

    struct in_addr sin_addr; // Internetaddress

    };The IP address structure , in_addr , isdefined as follows:

    struct in_addr{

  • 8/2/2019 Socket Prog 4

    14/33

    IP Addresses and How to Deal With Them

    e.g we have a struct sockaddr_in ina, and you have anIP address "10.12.110.57" that you want to store into it. Thefunction we will use is, inet_addr(), converts an IP addressin numbers-and-dots notation into an unsigned long. The

    assignment can be made as follows:

    ina.sin_addr.s_addr =inet_addr("10.12.110.57");

    inet_addr()returns the address in Network Byte

    Order.

    inet_addr() returns -1 on error.

  • 8/2/2019 Socket Prog 4

    15/33

    1.socket()Get the File Descriptor!

    CREATING A SOCKET

    #include #include

    int socket(int domain, int type, int

    protocol);First, domain should be set to"AF_INET specifies the address family used by programscommunicating across a TCP/IP n/w including the internet.Next, the type argument tells the kernel what kind of socketthis is: SOCK_STREAMor SOCK_DGRAM.Finally, just setprotocol to "0" (by default),choose the correct protocol

    based on the type and domain. There is normally no

    choice. socket() simply returns to you a socket

    descriptor , or -1 on error. When the socket has beenconnected to another endpoint socket, we can use the read

  • 8/2/2019 Socket Prog 4

    16/33

    NAMING A SOCKETbind()What port am Ion?#include

    #include

    server_address.sun_family=AF_UNIX;

    strcpy(server_address.sun_path,server_socket)

    ;

    server_len=sizeof(server_address);

    int bind(int sockfd, (struct sockaddr*)my_addr, int addrlen);

  • 8/2/2019 Socket Prog 4

    17/33

    Bind (server_sockfd,(struct sockaddr*)&server_address, server_len),

    sockfd is the socket file descriptor returned by socket().my_addr is a pointer to a struct sockaddr that

    contains information about your address, namely, port andIP address. addrlen can be set to sizeof(structsockaddr).

    R i C i

  • 8/2/2019 Socket Prog 4

    18/33

    Requesting Connection

    connect( )

    E.g telnet application.We called socket(). Next, the user

    tells you to connect to"10.12.110.57" on port "23" (thestandard telnet port.) we will call connect( )how to

    connect to a remote host. The connect() call is as

    follows:

    #include

    #include

    int connect(int sockfd, struct sockaddr

    *serv_addr, int addrlen);

    sockfd issocket file descriptor, as returned by thesocket() call, serv_addris a struct sockaddrcontaining the destination port and IP address, and addrlen

    can be set to iz f r k r .This

  • 8/2/2019 Socket Prog 4

    19/33

    listen( )

    CREATING A SOCKET QUEUE

    If you dont want to connect to a remote host, that you want to

    wait for incoming connections and handle them in some way

    in a server programmer. The process is two step:

    first you listen(), then

    you accept()

    int listen(int sockfd, int backlog);

    sockfd is the usual socket file descriptor from the socket()system call. backlog is the number of connections allowed onthe incoming queue. Most systems silently limit this number to

    about 20; you can probably set it to 5 or 10.

  • 8/2/2019 Socket Prog 4

    20/33

    The sequence of system calls youll make is:

    socket( );

    bind( );

    connect( );

    listen( );

    accept( );

  • 8/2/2019 Socket Prog 4

    21/33

    accept()Someone far far away will try to connect() to yourmachine on a port that you are listen()ing on. Their connectionwill be queued up waiting to be accepted. You call accept() and

    you tell it to get the pending connection. Itll return to you a brandnew socket file descriptor to use for this single connection.The

    original one is still listening on your port and the newly created one

    is finally ready to send() and recv(). #include

    int accept(int sockfd, void *addr, int *addrlen);

    int accept(int socket,struct sockaddr*address,size_t *address_len);

    sockfd is the listen()ing socket descriptor, addr will usually be apointer to a local struct sockaddr_in. This is where theinformation about the incoming connection will go (and with it you

    can determine which host is calling you from which port). addrlen is

    a local integer variable that should be set to sizeof(struct

  • 8/2/2019 Socket Prog 4

    22/33

    If it puts fewer in, itll change the value ofaddrlen to reflectthat.

    The accept system call returns when a client program attempts

    to connect to the socket specified by the parameter socket.The

    client is the first pending connection from that sockets

    queue.the new socket will have the same type as the server listen

    socket.

    d() d ()

  • 8/2/2019 Socket Prog 4

    23/33

    send() and recv()

    These two functions are for communicating over stream

    sockets or connected datagram sockets. If you want to

    use regular unconnected datagram sockets,then we haveto see sendto() and recvfrom(),

    The send() call:

    int send(int sockfd, const void *msg,int len, int flags);

    sockfdis the socket descriptor you want to send data to(whether its the one returned by socket() or the one

    you got with accept().) msgis a pointer to the datayou want to send, and lenis the length of that data inbytes. Just set flagsto 0.

    send() returns the number of bytes actually sent out

    this mi ht be less than the number ou told it to send!

  • 8/2/2019 Socket Prog 4

    24/33

    Some sample code might be:

    char *msg = "Beej was

    here;

    int len, bytes_sent;

    len = strlen(msg);

    bytes_sent = send(sockfd,msg, len, 0);

  • 8/2/2019 Socket Prog 4

    25/33

    int recv(int sockfd, void *buf, intlen, unsigned int flags);

    sockfd is the socket descriptor to read from, buf is the

    buffer to read the information into, len is the maximumlength of the buffer, and flags can again be set to 0. recv()

    returns the number of bytes actually read into the buffer, or

    -1 on error.

  • 8/2/2019 Socket Prog 4

    26/33

    sendto() andrecvfrom()Since datagram sockets arent connected to a remote host,

    so we have to send piece of information we need to givebefore we send a packet i.e the destination address.

    int sendto(int sockfd, const void*msg, int len, unsigned int

    flags,const struct sockaddr *to, inttolen);

    This call is basically the same as the call to send() with

    the addition of two other pieces of information. * tois apointer to a struct sockaddr (which we have as astruct sockaddr_in ) which contains the destination

    IP address and port. tolencan simply be set tosizeof(struct sockaddr).

  • 8/2/2019 Socket Prog 4

    27/33

    Equally similar are recv() and recvfrom().

    int recvfrom(int sockfd, void *buf, int len,unsigned int flags,

    struct sockaddr *from, int *fromlen);

    Again, this is just like recv() with the addition of a couplefields. * fromis a pointer to a local struct sockaddr that

    will be filled with the IP address and port of the originatingmachine. *fromlenis a pointer to a local int that should beinitialized to sizeof(struct sockaddr). When thefunction returns, fromlenwill contain the length of the address

    actually stored in from.recvfrom() returns the number of bytes received, or -1 on

    error (with errnoset accordingly.)Remember, if youconnect() a datagram socket, you can then simply use

    send() and recv() for all your transactions. The socketitself is still a data ram socket and the ackets still use UDP but

  • 8/2/2019 Socket Prog 4

    28/33

    close() andshutdown()

    close(sockfd);This will prevent any more reads and writes to the socket.

    Anyone attempting to read or write the socket on there end

    will receive an error. Just in case you want a little more

    control over how the socket closes, you can use theshutdown() function. It allows you to cut off

    communication in a certain direction, or both ways (just

    like close() does.)

    int shutdown(int sockfd, int how);

  • 8/2/2019 Socket Prog 4

    29/33

    gethostname( )

    Even easier than getpeername() is the function

    gethostname(). It returns the name of the computer thatyour program is running on. The name can then be used bygethostbyname(), to determine the IP address of your

    local machine

    #include int gethostname(char *hostname, size_tsize);

    The arguments are simple: hostnameis a pointer to an

    array of chars that will contain the hostname upon the

    functions return, and sizeis the length in bytes of the

    hostnamearray.

    The function returns 0 on successful completion, and -1on error, setting errnoas usual.

  • 8/2/2019 Socket Prog 4

    30/33

  • 8/2/2019 Socket Prog 4

    31/33

    Client-Server Background

    Just about everything on the network deals with client

    processes talking to server processes and vice-versa. Taketelnet, for instance. When you connect to a remote host on

    port 23 with telnet (the client), a program on that host

    (called telnetd, the server) comes to life. It handles the

    incoming telnet connection, sets you up with a login prompt,

    etc. Client-Server pair can speak SOCK_STREAM,SOCK_DGRAM, or anything else (as long as theyre speaking

    the same thing.) Some good examples of client-server pairs

    are telnet/telnetd, ftp/ftpd, or bootp/bootpd. Every time you

    use ftp, theres a remote program, ftpd, that serves you.Often, there will only be one server on a machine, and that

    server will handle multiple clients using fork(). The basicroutine is: server will wait for a connection, accept() it,and fork() a child process to handle it. .

  • 8/2/2019 Socket Prog 4

    32/33

    What to do to be a Server

    Call socket():A call to socket() with the proper argumentscreates the socket.1. Call bind(): You got a socket descriptor from the call to

    socket(), now you want to bind that to an address in

    the Unix/linux domain..2. Call listen(): This instructs the socket to listen for

    incoming connections from client programs.3. Call accept(): This will accept a connection from a

    client. This function returns another socket descriptor!

    The old descriptor is still listening for newconnections, but this new one is connected to theclient:

    5. Handle the connection and loop back to accept():

    Usually you'll want to communicate to the client (we'll

  • 8/2/2019 Socket Prog 4

    33/33

    6. Close the connection: You can close theconnection either by calling close(), or by calling

    shutdown().What to do to be a client

    There needs to be a program to talk to the aboveserver.

    1.Call socket() to get a Unix domain socket tocommunicate through.2. Set up a struct sockaddr_un with the remote

    address (where the server is listening) and callconnect() with that as an argument

    3. Assuming no errors, you're connected to theremote side! Use send() and recv() to your heart's

    content!

    http://www.ecst.csuchico.edu/~beej/guide/net/http://www.ecst.csuchico.edu/~beej/guide/net/