NW LAB 1. Basics of Socket Programming in C : TCP and UDP - Program Demo
Summary
TLDRThis video tutorial delves into the fundamentals of socket programming in C, showcasing TCP and UDP implementations. It explains sockets as endpoints for network communication, detailing their structure with IP addresses and port numbers. The video distinguishes between datagram and stream sockets, utilizing UDP and TCP respectively, and touches on raw sockets for security applications. It proceeds to illustrate the Berkeley Socket API, covering essential socket functions and their usage in client-server models. The script also includes practical examples of TCP and UDP server-client communication, demonstrating the process from socket creation to data transfer and closure.
Takeaways
- 🔌 A socket is an endpoint for two-way communication between programs on a network, providing a bi-directional FIFO communication facility.
- 📍 Each socket has a unique address composed of an IP address and a port number, crucial for establishing connections in client-server applications.
- 🛠️ There are three main types of sockets: datagram (UDP), stream (TCP), and raw sockets, each with distinct transport layer protocols and use cases.
- 🔗 TCP provides a connection-oriented, reliable, and bi-directional protocol with acknowledgements and retransmissions, ensuring data integrity.
- 🌐 UDP is a connectionless protocol without the guarantees of order, acknowledgements, or duplicate protection, offering less overhead.
- 🔍 Raw sockets allow for direct IP packet manipulation, used in security and diagnostic tools like Nmap, IGMP, and ICMP utilities.
- 📚 Berkeley sockets, the focus of the script, use the Berkeley Socket API, which is demonstrated through various socket functions in the script.
- 🔧 Key socket functions include socket creation, binding, listening (for servers), connecting (for clients), and data transfer via send/receive or sendto/recvfrom.
- 📡 The script explains the importance of network byte order for port and address specifications in socket functions, contrasting with host byte order.
- 🔄 Functions like htons and inet_addr are used for converting host data to network byte order and IP addresses to a format usable in socket operations.
- 📝 The script outlines a step-by-step implementation of both TCP and UDP server and client programs, detailing the process of creating sockets, handling connections, and data transfer.
- 🖥️ The video concludes with demonstrations of running TCP and UDP server and client programs, showing practical application of the discussed concepts.
Q & A
What is a socket in the context of network programming?
-A socket is one endpoint of a two-way communication link between two programs running on a network, providing a bi-directional FIFO (First In, First Out) communication facility over the network.
What is the purpose of the 'socket' function in C?
-The 'socket' function in C is used to create an endpoint for communication and returns a file descriptor that refers to that endpoint.
What are the two main types of sockets used in transport layer protocols?
-The two main types of sockets used in transport layer protocols are datagram sockets, which use UDP, and stream sockets, which use TCP.
What is the difference between TCP and UDP protocols?
-TCP (Transmission Control Protocol) is a connection-oriented protocol that is reliable and bi-directional, ensuring data integrity with acknowledgements and retransmissions. UDP (User Datagram Protocol) is a connectionless protocol that does not guarantee data delivery, allowing packets to arrive out of order and duplicates to occur.
What is a raw socket and what is it used for?
-A raw socket allows direct sending and receiving of IP packets without any protocol-specific transport layer formatting. It is used in security-related applications like network scanners (e.g., nmap) and in routing protocols like IGMP and ICMP.
What are the three arguments of the 'bind' function in socket programming?
-The 'bind' function has three arguments: the socket descriptor, a pointer to the 'sockaddr_in' structure, and the length of that structure.
What is the purpose of the 'listen' function in TCP socket programming?
-The 'listen' function marks a socket as a passive socket that will be used to accept incoming connection requests, with a specified maximum length for the queue of pending connections.
How does the 'connect' function in socket programming work?
-The 'connect' function attempts to establish a connection to a specified socket. If successful, it returns 0; otherwise, it returns -1 indicating an error.
What is the role of the 'accept' function in server-side TCP socket programming?
-The 'accept' function is used on the server side to extract the first connection request from the queue of pending connections for the listening socket and create a new connected socket, returning a new file descriptor for the connection.
What are the two flags mentioned for the 'send' function in TCP socket programming?
-The two flags mentioned for the 'send' function are 'MSG_MORE', which indicates that the caller has more data to send, and 'MSG_EOF', which is used for terminating a record.
What is the difference between the 'send' and 'sendto' functions in socket programming?
-The 'send' function is used in connection-oriented protocols like TCP, while 'sendto' is used in connectionless protocols like UDP. 'sendto' requires additional parameters for the destination address and its length.
What is the purpose of the 'inet_addr' function in socket programming?
-The 'inet_addr' function converts a string in standard IPv4 dotted decimal notation to an integer value suitable for use as an Internet address.
What is the significance of network byte order in socket programming?
-Network byte order is a method of sorting bytes that is independent of specific machine architecture and is used to ensure that data is transmitted in a consistent format across different systems. It is always defined to be big endian.
What is the role of the 'close' function in socket programming?
-The 'close' function is used to deallocate the file descriptor associated with a socket. If executed successfully, it returns 0; otherwise, it returns -1 indicating an error.
Outlines
🔌 Introduction to Socket Programming in C
This paragraph introduces the concept of socket programming in C, explaining that a socket is an endpoint for two-way communication between programs over a network. It discusses the creation of sockets at each end of the communication link, their specific addresses composed of an IP address and port number, and their role in client-server applications. The paragraph also distinguishes between different types of sockets, such as datagram, stream, and raw sockets, and the protocols they use, namely UDP and TCP for datagram and stream sockets, respectively. Raw sockets are highlighted for their use in security applications, and the Berkeley Socket API is introduced as the basis for the subsequent discussion.
📚 Socket Functions and Their Usage
The second paragraph delves into the specific functions used in socket programming, focusing on the server and client perspectives for both TCP and UDP protocols. It outlines the functions 'socket', 'bind', 'listen', 'accept', 'connect', 'send', 'receive', and 'close', explaining their purpose and parameters. For TCP, the server uses 'bind', 'listen', and 'accept', while the client uses 'connect'. For UDP, both server and client use 'socket', 'bind', 'sendto', 'recvfrom', and 'close'. The paragraph also describes the 'sockaddr_in' structure for storing address information and the importance of network byte order in socket function calls.
📝 Detailed Explanation of TCP/IP Functions
This paragraph provides a detailed explanation of the functions used in TCP and UDP communication, including 'send', 'sendto', 'receive', and 'recvfrom'. It discusses the parameters of these functions and the significance of flags in controlling message transmission. The paragraph also introduces auxiliary functions like 'htons' for converting to network byte order, 'inet_addr' for converting IP addresses, and 'strcpy' for string copying. It highlights the structures used for storing address information and the difference between network and host byte order, emphasizing the use of big-endian byte order for network communication.
🖥️ Implementation of TCP Server and Client Programs
The fourth paragraph outlines the implementation of a TCP server and client program. It describes the process of creating a socket, binding it to an address, listening for connections, accepting client requests, and transferring data using 'send' and 'receive' functions. The paragraph details the steps involved in initializing socket structures, converting port numbers, binding to localhost, and handling data transfer between the server and client. It also explains the use of 'inet_addr' for IP address conversion and the importance of closing the socket after communication is complete.
🌐 UDP Server and Client Program Implementation
This paragraph focuses on the implementation of UDP server and client programs. It explains the process of creating a UDP socket, binding it, and entering a listening mode to receive messages from the client. The paragraph details the use of 'recvfrom' and 'sendto' functions for message reception and transmission, including handling the source and destination addresses. It also discusses error handling, message sending, and closing the socket, providing a step-by-step guide for both server and client sides of a UDP communication.
🔄 Running TCP and UDP Programs for Demonstration
The final paragraph concludes the script by demonstrating the running of TCP and UDP server and client programs. It describes the process of compiling and running both server and client programs in separate terminals, emphasizing the need for two terminals since the programs run on the same system. The paragraph illustrates the interaction between the server and client, showing how messages are sent and received, and concludes with a thank you note to the viewers for watching the video.
Mindmap
Keywords
💡Socket
💡TCP (Transmission Control Protocol)
💡UDP (User Datagram Protocol)
💡IP Address
💡Port Number
💡Berkeley Sockets
💡Socket Functions
💡Data Transfer
💡Network Byte Order
💡Host Byte Order
💡Raw Sockets
Highlights
Introduction to the basics of socket programming in C.
Explanation of sockets as endpoints for network communication with bi-directional FIFO capabilities.
Socket address composition including IP address and port number.
Role of sockets in client-server applications with servers waiting for client connections.
Different types of sockets: datagram, stream, and raw sockets.
UDP and TCP protocols associated with datagram and stream sockets respectively.
TCP's reliability and bi-directionality contrasted with UDP's connectionless nature.
Raw sockets' use in security applications like Nmap and network protocols like IGMP and ICMP.
Berkeley sockets and the use of Berkeley Socket API for implementation.
Illustration of host communication through sockets and routers.
Detailed discussion of socket functions used in both TCP and UDP.
Function definitions for socket creation, binding, listening, connecting, accepting, sending, and receiving.
Use of sys/socket.h header file for socket functions.
Explanation of network byte order and its contrast with host byte order.
Functions htons and inet_addr for network byte order conversion and IP address interpretation.
Implementation of TCP server and client programs with code walkthrough.
Implementation of UDP server and client programs with code walkthrough.
Demonstration of running TCP and UDP server and client programs.
Conclusion and thanks for watching the networking lab video.
Transcripts
hello all welcome to this video on
networking lab today i'll be talking
about the basics of socket programming
in c
we also show the implementation of the
same using tcp and udp
let's begin with the topic socket
now a socket is
one end point of a two-way communication
link between two programs running on the
network
the socket provides bi-directional fifo
communication facility over the network
a socket connecting to the network is
created at each end of the communication
each socket has a specific address this
address is composed of an iep address
and a port number
sockets are generally employed in client
server applications the servers
create a socket attaches it to a network
port address and then waits for the
client to contact it
the client creates a socket and then
attempts to connect to the server socket
when the connection is established then
the transfer of data takes place
there are
different types of sockets available
like datagram socket
stream socket and row sockets
now datagram socket and
stream sockets
they vary in the transport layer
protocol that they use datagram sockets
use udp and stream sockets use tcp
tcp is a connection oriented protocol
which is reliable and bi-directional
whereas udp is a connectionless protocol
which has
no acknowledgements no retransmission
where packets might arrive out of order
and duplicates are possible
then we have the third type of socket
which is raw sockets
they allow direct sending and receiving
of ip packets without any protocol
specific transport layer formatting
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
the sockets that we are creating here
are called the berkeley sockets so we'll
be using the berkeley socket api for the
same
this picture shows how
two hosts
are communicating with each other
through the sockets now each socket will
have
its ip address and a port number
which is connected to each other through
a router
now we look into detail
into the various socket functions that
we'll be using here the diagram here
shows the different functions that are
used both in tcp and udp both at the
server and the client side
in tcp
both server and client use the functions
socket
send receive and close
now the functions bind
listen and accept are
for server in tcp and for client there's
a function called connect
as in the case of udp the server and the
client have functions socket bind
send to receive from and close
now we'll start by discussing about the
function which is socket
also note that all the
functions that we will be discussing
from now are defined in the header file
which is sys socket dot h
now looking into the function
in sock id
socket
int domain and type and end protocol
now this function socket will create an
end point for communication
and returns a file descriptor that
refers to that endpoint
now this file descriptor returned by a
successful call will be the lowest
numbered file descriptor that is not
currently opened for any process
now we look into the domain that's the
first argument
so domain will specify
the communication domain so in this case
you can have different options i have
shown two options here one is af inet
which is used for ipv4 internet protocol
and af unix which is used for local
communication
then the second argument is type which
is used to refer to communication
semantics that too we are using
the two commonly used options which is
soft stream
that is
used for
tcp connections which is sequenced
reliable
and
two-way connection based
then we have sock d gram which is used
in udp which supports datagrams
then the third option is
protocol
now the protocol will
specify the particular protocol that is
to be used with the socket normally only
a single protocol exists to support a
particular socket type within a given
protocol family in which case the
protocol field can be specified as
0.
now the status here is referring to the
return value of this function now if it
is successful then a value
which is
returned will be the
lowest
file descriptor number as we have seen
and if this value goes below zero that's
that is if it is minus one it means that
there was an error in it
now we look into the next function which
is bind
now here bind
has
three arguments
which are the socket descriptor followed
by a pointer to the
sock header in structure and the length
of that particular
structure
now this bind will assign the address
specified by the
second argument here to the socket
referred to the first argument
and we can also see this will store the
status of return value
and if it is
minus 1 it means there was a failure
else it will always return the value of
0.
then we will move on to the next
function which is listen
now the listen function has two
arguments which is
saw kefny and backlog now listen marks
the socket referred to by sock fd as a
passive socket that is as a socket that
will be used to accept the incoming
connection request
and the second argument backlog
defines the maximum length to which the
queue of pending connections can grow
now on successful execution of this
function it will return a zero
else it will return minus 1.
now we look into the next function so
here
first the client will be sending a
connect request to the server then it
will
execute the accept function first we
will see the connect function so looking
into connect function we have
three arguments here the
file descriptor
then the
pointer to the address structure and its
length
now
the connect function shall attempt to
make a connection to the particular
socket
now if the connection was successful
then it will return a zero else it will
return a minus one
next we will look into the function
accept which is run at the server end so
this is done when a request is received
from the client
it has arguments the file descriptor
then a pointer to the socket ring
structure and its length
now this will extract the first
connection request on the queue of
pending connections for the listening
socket
and create a new connected socket and
return the new file descriptor referring
to that socket
now that is the value that is stored in
this
variable s
next we look into the
functions that are used for sending and
receiving data at tcp and udp side
first we will move to the send function
that is used by
tcp
now send will have the arguments the
file descriptor
the buffer where the data to be sent is
stored
the length of
the data and flags
now this flags can be the or
of zero or more flags like
there are some options for available for
it
so we will see two of them
one of them is message mode which is
used to say that the caller has more
data to send and the other one is
message eor which is
used for terminating a record
now the return value here it is called
count which will contain the number of
bytes that is sent if there is an error
it will return a minus one value
now we will see send to that is used in
datagram sockets which is udp
here also we have the socket descriptor
buffer buffer size flags if any
and then we have
the destination address pointer and the
length of the destination address so
those two will be the extra fields that
we added when you use
send to
then we have
the receive function
here also we'll have a file descriptor
then the
buffer length of the buffer and flags
used
so here also we are discussing two flags
that are used and received
now which are
message
oob that is used to indicate
receiving out of band data
and then we have
message peak
which causes the receive operation to
return data from the beginning of the
received queue without removing that
data from the queue
here also we have a count variable where
the number of bytes received will be
stored else
that is if there is an error the value
will be minus 1.
in case of datagram socket it is
received from so there will be two extra
fields where we have the
source address and source address length
all the rest will be the same for both
now we are going to discuss the
functions
and the structures that will be using in
the implementation
of the program that we are going to see
shortly
so first of all we will be using a
structure called sock header in
where we will be using the peer address
that is used to store the peer address
so it is declared in the header file
that net inet slash in dot h
so this is this format
it has
three
members in it
the syn family member is referring to
the address family which is
in our case afinit
then we have sin underscore port which
is
used to store the port in network byte
order
then we have the third element which is
a structure that is used to store the
internet address
now the third
structure which is in adder
contains the element s
so that is where the address in network
byte order will be stored
now we will look into what this network
byte order is
now the ports and addresses are always
specified in calls to the socket
functions using the network byte order
convention
this convention is a method of sorting
bytes that is independent of specific
machine architecture
now host byte order on the other hand
sorts bytes in the manner which is most
natural to the host
software and hardware
there are two common host byte methods
that are used one is little indian and
the other is big indian
little indian bite ordering places the
least significant bite first followed by
the next higher ones
and big endian bite ordering places the
most significant bite first followed by
the
less higher ones after that
the network byte order is defined always
to be big endian
next we will be using a function called
h tones which is defined either in r
slash iron dot h or net inet slashing
dot h now this depends on different
systems so in the program we are going
to discuss i will be including both the
header files
now
we'll be looking what h stance is used
for it is used to translate an unsigned
short integer into its
network byte order
then we will be using the function i net
adder which is
defined in the header file rpa slash
init dot h
now in editor is a function that will
convert the string which is pointed to
by
cp variable
in the standard ipv4 dotted decimal
notation to an integer value that is
suitable for use as an internet address
so in our case this address will be
127.0.0.1 which is the localhost or
loopback address
then we will be also using our structure
sock header storage which is defined in
slash socket.h
now this structure
is large enough to accommodate all
supported protocol specific address
structures
then we use a type called socklin
underscore team
now
this is an integer type of width of at
least 32 bits
then we use the close function which is
defined in
uni std dot h that is
used to
deallocate the file descriptor
and if it is
successfully executed then 0 shall be
returned else it is -1 then we have
string copy and get s of string.h header
file
string copy is used to copy the value of
string from source to destination gettus
is used to get the value from standard
input which is the keyboard
we will be also using the function exit
which is defined in
stdlib dot h
now it is used to show
the exit status so in our case we are
using it to show the abnormal
termination so i'll be using exit and
the
status value as
1.
now we'll look into the implementation
first we'll be going through the tcp
server program i've included all the
header files that are to be used
then i'll define
a file descriptor server
to which the return value of socket
function is stored since it's tcp and
ipv4 i'm including a finite stock stream
and since ip protocol is used i'll
include
0. then i'll declare a variable for soc
header in
structure which is server and i'll
initialize the three values just family
afi net
and port number i'll convert this port
into the
required format using the function h
stones
then the third
member which is a structure
i'll take the local host address and
convert it using init editor to the
internet address and store it there
then i'll be binding it that is done by
including the file descriptor and a
pointer to the socket structure that we
created just now and its size
then after binding the server enters
into listening mode so listen off the
file descriptor comma the backlog length
which in my case is five now if this is
successful we'll print the message that
is listening else will print that there
is an error
now after listening the request is
received from the client and the server
will be accepting it so
accept
will contain the file descriptor and the
pointer to the structure and its length
now this will be the new file descriptor
through which data will be
transferred
now since it's the server it is waiting
to receive a message from the client so
since it's tcp i'll use the receive
function
the file descriptor buffer
buffer size is
given as 1024. that is taken with the
assumption that the data transfer
size will be 1 kb
now i am giving the full size of buffer
since i am unaware of the size of data
from the client and 0 because there are
no flags used then i'm printing the data
i received
that is stored in buffer
then i'll copy the data i need to send
to the client to buffer using string
copy
then i'll print a message showing that i
am sending data to client then i will
send it using the send function with the
file descriptor buffer and the size of
the string that i stored in buffer and 0
because there are no flags after all
this communication is over i'll close
both the listening socket and the socket
use for data transfer now looking into
the tcp client
we'll use
the same steps
where i had the client file descriptor
and the
sock adder in
structure which are initialized with
these values
now
next step is to
send a connection request to the server
so i'll include the file descriptor
pointer to the structure and the size of
the structure then i'll print that i'm
sending a message to the server
then i'll take the string copy to buffer
and send it to the
server
mentioning the file descriptor buffer
size of the string and 0 because there
are no flags
now the client is waiting for a message
from the server
for that you will be using the receive
function you have the file descriptor
buffer
full size of buffer because i don't know
the size of data that is coming from the
server side and 0 because no flags are
used then i'll print the receive data
and finally close the
socket
next we will see the implementation for
udp server and client we'll begin with
udp server i have included all the
header files
here i'll have two variables
for socket or instructure and two
message
variables too
then i'll store
the client address size to a variable
now this is optional you can either give
this directly in the function also
here
i am creating a udp
socket so ipv4 refine it soft drum
because it's udp
and this option here
is similar to the zero we saw before so
if you are using ip protocol you can
either give it as 0
or you can give it
specifically like this since its udp i
gave it as ip proto underscore udp if
it's tcp you can give the option ip
proto underscore tc
now i am checking if
this server value is less than 0 it
means there is an error and i will give
an abnormal termination
otherwise what i'll do is i'll print the
message socket was created successfully
then i will initialize these members of
this structure
as we did before so i'll be using a
different
port number here
then i'll do the binding taking the file
descriptor pointer to the structure and
its size now if this is less than 0 then
the binding has not happened and there
is an abnormal termination otherwise the
binding is done then the server enters
into a listening mode
then the server is waiting for a message
from the client so it is received from
function
the file descriptor variable where the
data
receivably stored size of it
no flags so it's zero
then the address of the
source and its length now if this is
less than zero again there was some
error abnormal termination else what it
does is it will
print the message received
and you can copy it to another variable
using string copy
then i need to send a message to the
client so i'll use the send to function
i'll mention the file descriptor the
message variable its length no flags so
it is 0
then the address of the sender and size
of the address now if it is less than 0
then there is an error abnormal
termination else the message will be
printed at the other side and finally
i'll close the socket
now looking at the client side the same
thing is done
creating the file descriptor checking if
it's less than zero if it is less
then it's terminated
otherwise successfully created
initializing the structure variables
then asking the client to enter a
message that is to be sent to the server
and reading it through the
get this function
then we'll have the send to function to
send the message to the udp server
file descriptor message variable size
flag
then the
destination address its length if less
than 0
then abnormal termination
else
it will be waiting for receiving message
from the service side same thing as
server then if there is an error it is
printed else the socket is closed
now we'll be looking into
the
tcp implementation
now we have the programs for tcp server
which we discussed before
then we have the program for tcp client
since we are running both on the same
system we need two terminals so i'll be
running it
at the same time one for server and one
for client i'll compile the server
program
then i'll run it first so it will be in
the listening mode then i'll combine
the
client program and run it
so it will send the message
now here
we have
the message already set in the program
as we have discussed
now we look into the same for udp
implementation
here also we'll have two terminals
first of all we'll run the
server program we'll first compile it
and run it
so it will be waiting for the client
message
then we'll do the same for the client
compile it and run it
there's a warning i'm ignoring it for
the time being
now after running the program it is
asking me to enter a message to be sent
to server i'm sending the message hi
so that is print
at the server side also
that's all for now thank you for
watching
Weitere ähnliche Videos ansehen
Sockets Tutorial with Python 3 part 1 - sending and receiving data
Advanced Networking - #7 TCP/IP & UDP/IP [EN]
Introduction to IP - CompTIA A+ 220-1001 - 2.1
Common Ports - CompTIA Network+ N10-009 - 1.4
Understanding Protocols, Ports and Sockets | Intro to Computer Networks Course Preview
Types Of Network Protocol | TCP | IP | UDP | POP | SMTP | FTP | HTTPS |Computer Networks|Simplilearn
5.0 / 5 (0 votes)