CNS assignment 9
CNS assignment 9
CNS assignment 9
Theory:
The Berkeley socket development library has many associated header files. They include:
<sys/socket.h>
Definitions for the most basic of socket structures with the BSD
socket API <sys/types.h>
Basic data types associated with structures within the BSD
socket API <netinet/in.h>
Definitions for the socketaddr_in{} and other base data structures.<sys/un.h>
Definitions and data type declarations for SOCK_UNIX streams
UDP:
UDP consists of a connectionless protocol with no guarantee of delivery. UDP packets may arrive
out of order, become duplicated and arrive more than once, or even not arrive at all. Due to the
minimal guarantees involved, UDP has considerably less overhead than TCP. Being connectionless
means that there is no concept of a stream or connection between two hosts, instead, data arrives in
datagrams.
UDP address space, the space of UDP port numbers (in ISO terminology, the TSAPs), is completely
disjoint from that of TCP ports. ]
Server:
while (1)
{
printf ("recv test....\n");
recsize = recvfrom(sock, (void *)hz, 100, 0, (struct sockaddr *)&sa, fromlen);
printf ("recsize: %d\n ",recsize);
if (recsize < 0)
fprintf(stderr, "%s\n", strerror(errno));
sleep(1);
printf("datagram: %s\n",hz);
}
This infinite loop receives any UDP datagrams to port 7654 using recvfrom(). It uses the
parameters:
• socket
• pointer to buffer for data
• size of buffer
• flags (same as in read or other receive socket function)l address struct of sending peer
• length of address struct of sending peer.
Client:
A simple demo to send an UDP packet containing "Hello World!" to address 127.0.0.1, port 7654
might look like this:
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
int main(int argc, char *argv[])
{
int sock;
struct sockaddr_in sa;
int bytes_sent, buffer_length;
char buffer[200];
sprintf(buffer, "Hello World!");
buffer_length = strlen(buffer) + 1;
sock = socket(PF_INET, SOCK_DGRAM, 0);
sa.sin_family = AF_INET;
sa.sin_addr.s_addr = htonl(0x7F000001);
sa.sin_port = htons(7654);
bytes_sent = sendto(sock, buffer, buffer_length, 0, &sa,
sizeof(struct sockaddr_in) );
if(bytes_sent < 0)
printf("Error sending packet: %s\n", strerror(errno) );
return 0;
}
In this code, buffer provides a pointer to the data to send, and buffer_length specifies the size of the
buffer contents.
Typical UDP client code
1. Create UDP socket to contact server (with a given hostname and service port number)
2. Create UDP packet.
3. Call send(packet), sending request to the server.
4. Possibly call receive(packet) (if we need a reply).
APPLICATION
Socket programming is essential in developing any application over a network.