Basis of Socket Programiing

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 50

Basics of Socket Programming in C

1
What is a socket?

• Socket: socket is one end point of a two-way communication link between


two programs running on the network

•The application process can send/receive messages to/from another application

process (local or remote)via a socket


•socket has a specific address called socket address which is composed of an ip

address and a port number


•sockets are generally employed in client server applications

2
Types of Sockets:
 Internet Sockets
 unix sockets,
 X.25 sockets etc

• Berkeley sockets is the most popular Internet Socket


– runs on Linux, FreeBSD, OS X, Windows
– fed by the popularity of TCP/IP

 Internet sockets characterized by IP Address (4 bytes) and port number (2


bytes)

3
Types of Internet Sockets

• Stream Sockets (The socket type is SOCK_STREAM)

• Datagram Sockets (The socket type is SOCK_DGRAM)

• RAW SOCKET( The socket type of Raw Socket is

SOCK_RAW.)

4
Types of Internet Sockets
 Stream Sockets (SOCK_STREAM)
 Connection oriented
 Rely on TCP to provide reliable two-way connected communication

 Datagram Sockets (SOCK_DGRAM)


 Rely on UDP
 Connection is unreliable

5
Raw sockets

• They allow direct sending and receiving of ip packets without any


protocol
• They are used in security related applications like nmap which is a
network scanner that is used to discover hosts and services on a
computer network by sending packets and analyzing their responses
• It is also used in routing protocols like IGMP which is internet group
management protocol and in ICMP which is internet control
message protocol that is used in the ping utility

6
Byte ordering.
. Integers are stored in memory and sent across the network as sequences of
bytes.
• different machines / OS’s use different word orderings
Address and port are stored as integers
There are two common ways of storing these bytes or ordering of bytes
Big Endian vs. Little Endian
 Little Endian (Intel, DEC):
 Least significant byte of word is stored in the lowest memory address
 Big Endian (Sun, SGI, HP):
 Most significant byte of word is stored in the lowest
memory address

7
 For instance, the value A1B2C3D4 (2712847316 in decimal)
can have two forms, as given below:

8
Consider a situation where a Little Endian system wants to communicate with a
Big Endian one,
if there is no standard for data representation then the data sent by one machine is
misinterpreted by the other.
So standard has been defined for the data representation in the network
---Network Byte Order which is the Big Endian.
 Data transmitted on a network is sent in the network byte order
when data needs to be transmitted over a network, we need to change the byte
ordering to the network byte order

9
Any words sent through the network should be converted to
Network Byte-Order prior to transmission (and back to
Host Byte-Order once received)

10
Byte Ordering Functions

The system calls that help us to convert a short/long from Host Byte
order to Network Byte Order and viceversa are
Conversions:
htons() - Host to Network Short
htonl() - Host to Network Long
ntohs() - Network to Host Short
ntohl() - Network to Host Long

11
htons host to network short :
convert a number into a 16-bit network representation.
This is commonly used to store a port number into a sockaddr
structure.

htonl host to network long :


convert a number into a 32-bit network representation.
This is commonly used to store an IP address into a sockaddr
structure.

12
ntohs network to host short :
convert a 16-bit number from a network representation into the local
processor's format.
This is commonly used to read a port number from a sockaddr structure.
ntohl network to host long :
convert a 32-bit number from a network representation into the local processor's
format.
This is commonly used to read an IP address from a sockaddr structure.

13
Procedure of Socket Programming
In order to communicate between two processes, the two
processes must provide the information used by TCP/IP (or
UDP/IP) to exchange data.

This information is the 5-tupe:

{protocol, local-addr, local-process, foreign-addr,


foreign-process}.

Several network systems calls are used to specify this


information and use the socket.

14
Socket functions in C

15
Socket functions in C

16
socket() -- Get the file descriptor
#include <sys/socket.h>
syntax:
int socket(int family, int type, int protocol);
• Family is the address family specification
• It can be
• Name Purpose
• AF_INET IPv4 Internet protocols
• AF_INET6 IPv6 Internet protocols
• AF_UNIX Unix Internet protocols
AF means address family
17
Type: It specifies the semantics of communication , or the type
of service that is desired .
It takes the following values:
• SOCK_STREAM : Stream Socket ,reliable ,connection
based
• SOCK_DGRAM : Datagram Socket ,unreliable
connectionless
• SOCK_RAW : Raw Socket
• SOCK_SEQPACKET : Sequenced Packet Socket
• SOCK_RDM : Reliably Delivered Message Packet

18
 Protocol: This parameter identifies the protocol the socket is supposed to use .
Some values are as follows:
 IPPROTO_TCP : For TCP (SOCK_STREAM)
 IPPROTO_UDP : For UDP (SOCK_DRAM)

• Normally set to 0 (use default protocol)

• returns a socket descriptor, -1 on error.

19
int s;
s= socket(AF_INET, SOCK_STREAM, 0)

20
Socket Address Structure
struct sockaddr_in: (TCP or UDP address)
• This construct holds the information about the address
family, port number, Internet address,and the size of the
struct sockaddr.
struct sockaddr_in {
short int sin_family; // set to AF_INET
unsigned short int sin_port; // Port number
struct in_addr sin_addr; // Internet address
unsigned char sin_zero[8]; //set to all zeros
}

21
struct in_addr(IP address)

struct in_addr {
in_addr_t s_addr; /* 32-bit IP address */
};

22
struct sockaddr_in server;

server.sin_family = AF_INET;
/* set the type of connection to TCP/IP */

server.sin_addr.s_addr = htonl(INADDR_ANY);
/* set our address to any interface */ //use my IP addr

server.sin_port = htons (3000);


/* set the server port number */

23
The specific form of the sockaddr structure that is used for the TCP/IP
socket addresses is the sockaddr_in structure.

This requires that any calls to these functions must cast the pointer to the protocol
specific socket address structure (our TCP/IP stuff) to be a pointer to a generic
socket address structure (the original generic stuff).

24
bind() - what port am I on?

• Used to associate a socket with a port on the local machine


• used to assign address to an existing socket..
• Syntax:
• int bind(int sockfd, struct sockaddr *my_addr, int addrlen)
• sockfd is the socket descriptor returned by socket()
• my_addr is pointer to struct sockaddr that contains information
about your IP address and port
• addrlen is set to sizeof(struct sockaddr)
• returns -1 on error

25
Notes:
 bind assigns the local IP address and port number to the socket.

 2) Servers call bind() to their well-known port to the socket. If a server omits the call to bind(), the kernel
selects an ephemeral port.

 3) Normally a TCP client doesn’t bind an IP address and port to its socket. The kernel chooses the IP
address and port number when connect() is called. A UDP client uses bind( ) so that incoming packets can
be delivered to it by the kernel.
 4) Using a wildcard, INADDR_ANY, for the IP address allows the server to accept a client connection on
any IP interface in case that server host has multiple interfaces or use servers own IP address

26
 bind(s,(struct sockaddr*)&server, sizeof(server));

27
connect(): Making TCP Connection to Server

Syntax:
int connect (int sockfd, struct sockaddr* servaddr, int addrlen);

• Connect to another socket.


• Returns 0 on success, -1 on failure.
• sockfd: socket file descriptor (returned from socket)
• servaddr: IP address and port number of server
• addrlen: length of address structure = sizeof (struct
sockaddr_in)

28
notes
1)connect( ) sets the local and foreign addresses and port numbers.

2) It initializes an active request for connection between the client


and the server.

3) It blocks until the connection is established.

4) Mainly used connection-oriented protocols, e.g., TCP.

29
connect(s,(struct sockaddr*)&server,sizeof(server));

30
listen() - Call me please!
• Waits for incoming connections

Syntax: int listen(int sockfd, int backlog);

• sockfd is the socket file descriptor returned by socket()

• backlog is the number of connections allowed on the incoming queue


( usually specified as 5)

• Need to call bind() before you can listen()


• Returns 0 if listening, else returns -1 if error
31
 listen(s,3);

32
accept() - Thank you for calling !
• accept() gets the pending connection on the port you are listening on

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

• sockfd is the listening socket descriptor


• Information about incoming connection is stored in addr
which is a pointer to a local struct sockaddr_in
• addrlen is set to sizeof(struct sockaddr_in)

 accept returns a new socket file descriptor to use for this accepted
connection or returns -1 on error

33
accept() continued

 Accept() system call creates another socket descriptor with the same properties
as sd (the socket descriptor returned earlier by the socket() system call).

 The new socket descriptor handles communications with the new client while
the earlier socket descriptor goes back to listening for new connections.

 In a sense,the accept() system call completes the connection

 At the end of a successful accept(), all elements of the five tuples of a


connection is filled

34
Int c;
c = accept(s,(struct sockaddr*)&client, &len);

35
36
Receiving Data (TCP)

37
 read(c,msg,20);

38
Sending Data(TCP)

39
write(c,msg,sizeof(msg));

40
Sending Data (UDP)

41
Receiving Data (UDP)

42
close() - Bye Bye!

43
bzero()

• This function will be used to set all the socket structures with
null values.
• Void bzero(char *dest, int nbytes);
• - *dest specifies pointer to buffer which has to be filled with
null bytes.
• This will be a pointer to socket structure variable
nbyte: specifies the number of bytes to be filled with null
values.
• This will be the size of the socket structure.

44
Server Example
#include<sys/socket.h>
#include<netinet/in.h>
#include<stdio.h>

void main() {
int s,c,len;
char msg[20]={""};
struct sockaddr_in server, client;
s=socket(AF_INET,SOCK_STREAM,0);
server.sin_family = AF_INET;
server.sin_port = htons(3000);
server.sin_addr.s_addr = htonl(INADDR_ANY);
bind(s,(struct sockaddr*)&server, sizeof(server));
listen(s, 10);
len = sizeof(msg);
c = accept(s,(struct sockaddr*)&client, &len);
CEN4500C
45
do {
printf("Message to Client: ");
gets(msg);
write(c,msg,sizeof(msg));
read(c,msg,20);
printf("Client: %s\n", msg);
} while(1);
close(c);
}

CEN4500C
46
Client Example
#include<sys/socket.h>
#include<netinet/in.h>
#include<stdio.h>

void main()
{
int c;
char msg[20]={""};
struct sockaddr_in server;
c=socket(AF_INET,SOCK_STREAM,0);
server.sin_family = AF_INET;
server.sin_port = htons(3000);
server.sin_addr.s_addr = htonl(INADDR_ANY);
CEN4500C
47
if(connect(c,(struct sockaddr*)&server,sizeof(server)));
{
while(1) {
read(c,msg,20);
printf("Server: %s",msg);
printf("\nMessage to Server: ");
gets(msg);
write(c,msg,sizeof(msg));
}
}
close(c);
}
48
 https://www.educative.io/answers/how-to-implement-tcp-
sockets-in-c

49
 bbb

50

You might also like