SlideShare ist ein Scribd-Unternehmen logo
1 von 34
Socket Programming in C/C++
Contents
• Socket
• Socket Structures
• Socket Functions
• TCP Example
– TCP Client
– TCP Server
• UDP Example
– UDP Client
– UDP Server
• Functions for Multicasting
Socket
• Socket
– Source ( IP , Port )
– Destination ( IP , Port )
– Protocol ( TCP , UDP , SCTP)
• Connection Oriented / Connection less
Socket Structures
• sockaddr
• sockaddr_in
– Connection information. Used by connect , send ,
recv etc
• in_addr
– IP address in long format
• hostent
– The IP addresses of a hostname. Used by
gethostbyname()
sockaddr , sockaddr_in & in_addr
hostent
Socket Functions
TCP UDP
socket
bind
listen
accept connect
write /send
read / recv
socket
bind
sendto
recvfrom
Socket Functions
socket: creates a socket of a given domain, type, protocol (buy a phone)
bind: assigns a name to the socket (get a telephone number)
listen: specifies the number of pending connections that can be queued for a
server socket. (call waiting allowed)
accept: server accepts a connection request from a client (answer phone)
connect: client requests a connection request to a server (call)
send, sendto: write to connection (speak)
recv, recvfrom: read from connection (listen)
shutdown: end the call
Sockets Functions used for TCP
Sockets Functions used for UDP
Socket Functions
• Supporting Functions
– For Port Numbers
• htons / htonl
– Host to Network Byte Order (short-16/long-32)
• ntohs/ntohl
– Network to Host Byte Order (short-16/long-32)
– For IP Address
• inet_ntoa
– convert an IP address to dotted format
• inet_addr
– convert an IP address to a long format
– For Host
• gethostbyname
Socket Functions
• Supporting functions Example
– htons & inet_addr
• struct sockaddr_in server;
• server.sin_port = htons( 80 );
• server.sin_addr.s_addr = inet_addr("74.125.235.20");
socket()
• int socket (int domain , int type , int protocol)
– domain (Address Family)
• AF_INET (IP version 4)
• AF_INET6 (IP version 6)
– Type :
• SOCK_STREAM (connection oriented TCP protocol)
• SOCK_DGRAM (connectionless UDP protocol)
– Protocol :
• 0 , (zero) to detect protocol according to the type
• IPPROTO_TCP
– returns Socket Descriptor on success
socket()
bind()
• int bind(int sid , struct sockaddr *addrptr , int len)
– sid :
• socket ID obtained through socket()
– *addrptr: (for local host)
• Family dependent address
• Used to bind IP and Port number to a socket
– len
• Length of the addrptr
bind()
listen()
• int listen(int sid , int size)
– sid:
• Socket descriptor obtained through socket()
– size:
• Number of connections that can be handled
concurrently
– returns 0 on success or -1 in failure
– Example
• listen ( socket_desc , 5 );
connect()
• int connect(int sid , struct sockaddr *addrptr , int len)
– sid :
• socket ID obtained through socket()
– *addrptr: (for remote host or Destination)
• Family dependent address
• Used to specify destination (IP and Port)
– len
• Length of the addrptr
– returns 0 on success and -1 on failure
connect()
accept()
• int accept(int sid , struct sockaddr *addrptr , int len)
– sid :
• socket ID obtained through socket()
– *addrptr: ( remote host who requested to connect)
• Family dependent address
• Used to get remote client address (IP and Port)
– len
• Length of the addrptr
– returns new sock descriptor and address of a remote
client who requested the connection by connect()
send() / recv()
• int send (int sid , const char *buffer, int len , int flag)
• Int recv (int sid , const char *buffer, int len , int flag)
• int sendto (int sid , const char *buffer, int len , int flag
struct sockaddr *addrptr, int addrptr_len)
• int recvfrom (int sid , const char *buffer, int len ,int flag
struct sockaddr *addrptr, int addrptr_len)
Getting IP of a host name/domain
• struct hostent * gethostbyname()
Functions for UDP communication
• int sendto
– int sid
– const char *buffer, int len , int flag
– struct sockaddr *addrptr, int addrptr_len
• int recvfrom
– int sid ,
– const char *buffer, int len , int flag
– struct sockaddr *addrptr, int addrptr_len
UDP Receiver
sd=socket(AF_INET, SOCK_DGRAM, 0);
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
servAddr.sin_port = htons(SERVER_PORT);
rc = bind (sd,(struct sockaddr *)&servAddr, sizeof(servAddr));
n = recvfrom(sd, msg, MAX_MSG, 0,(struct sockaddr *)&cliAddr ,
sizeof(cliAddr)
UDP sender
sd = socket(AF_INET,SOCK_DGRAM,0);
remoteServAddr.sin_family = AF_INET;
remoteServAddr.sin_addr.s_addr = htonl(SERVER_IP);
remoteServAddr.sin_port = htons(SERVER_PORT);
rc = sendto(sd, msg, strlen(msg)+1, 0,
(struct sockaddr *) &remoteServAddr,
sizeof(remoteServAddr));
Functions for Multicasting
• int getsockopt(
– int sid,
– int level, int optname, void* optval,
– int* optlen);
• int setsockopt(
– int sid,
– int level, int optname, const void* optval,
– int optlen);
• int IN_MULTICAST(ntohl(Addr.sin_addr.s_addr))
Multicasting – Function Arguments
• Socket ID
– AF_INET
– SOCK_DGRAM or SOCK_RAW
• Level (identifies the layer that is to handle the
option, message or query)
– SOL_SOCKET (socket layer)
– IPPROTO_IP (IP layer)
Multicasting – Function Arguments
• optname (option for multicasting)
setsockopt() getsockopt()
IP_MULTICAST_LOOP yes yes
IP_MULTICAST_TTL yes yes
IP_MULTICAST_IF yes yes
IP_ADD_MEMBERSHIP yes no
IP_DROP_MEMBERSHIP yes no
Options Value for Multicasting
• loopback
– u_char loop; // loop = 0 or 1
– setsockopt(socket, IPPROTO_IP, IP_MULTICAST_LOOP, &loop,
sizeof(loop));
• TTL
– u_char ttl; // default = 1 for own network only, 0 to 255
– setsockopt(socket, IPPROTO_IP, IP_MULTICAST_TTL, &ttl,
sizeof(ttl));
• Interface (multicast datagram sent from)
– struct in_addr interface_addr;
– setsockopt (socket, IPPROTO_IP, IP_MULTICAST_IF,
&interface_addr, sizeof(interface_addr));
Options Value for Multicasting
• Membership request structure
struct ip_mreq
{ /* IP multicast address of group */
struct in_addr imr_multiaddr;
/* local IP address of interface */
struct in_addr imr_interface;
};
• Add Members
– struct ip_mreq mreq;
– setsockopt (socket, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq,
sizeof(mreq));
• Drop Members
– struct ip_mreq mreq;
– setsockopt (socket, IPPROTO_IP, IP_DROP_MEMBERSHIP, &mreq,
sizeof(mreq));
Multicast Receiver
sd = socket(AF_INET,SOCK_DGRAM,0);
servAddr.sin_family=AF_INET;
servAddr.sin_addr.s_addr=htonl(INADDR_ANY);
servAddr.sin_port=htons(SERVER_PORT);
rc = bind(sd,(struct sockaddr *) &servAddr, sizeof(servAddr))
/* join multicast group */
mreq.imr_multiaddr.s_addr=mcastAddr.s_addr;
mreq.imr_interface.s_addr=htonl(INADDR_ANY);
rc = setsockopt(sd,IPPROTO_IP,IP_ADD_MEMBERSHIP,(void *) &mreq,
sizeof(mreq));
n = recvfrom(sd,msg,MAX_MSG,0,(struct sockaddr *) &cliAddr,&cliLen);
Multicast Sender
//simple UDP sender
sd = socket(AF_INET,SOCK_DGRAM,0);
setsockopt(sd,IPPROTO_IP,IP_MULTICAST_TTL, &ttl,sizeof(ttl)
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = htonl(SERVER_IP);
servAddr.sin_port = htons(SERVER_PORT);
rc = sendto(sd,argv[i],strlen(argv[i])+1,0,
(struct sockaddr *) &servAddr, sizeof(servAddr));

Weitere ähnliche Inhalte

Was ist angesagt?

Transmission Control Protocol (TCP)
Transmission Control Protocol (TCP)Transmission Control Protocol (TCP)
Transmission Control Protocol (TCP)k33a
 
Transport layer services
Transport layer servicesTransport layer services
Transport layer servicesMelvin Cabatuan
 
Socket programming in python
Socket programming in pythonSocket programming in python
Socket programming in pythonVignesh Suresh
 
Socket programming or network programming
Socket programming or network programmingSocket programming or network programming
Socket programming or network programmingMmanan91
 
Pipes in Windows and Linux.
Pipes in Windows and Linux.Pipes in Windows and Linux.
Pipes in Windows and Linux.Junaid Lodhi
 
One Time Pad Encryption Technique
One Time Pad Encryption TechniqueOne Time Pad Encryption Technique
One Time Pad Encryption TechniqueJohn Adams
 
IP Addressing and Subnetting
IP Addressing and SubnettingIP Addressing and Subnetting
IP Addressing and Subnettingcbtvid
 
Network address translation
Network address translationNetwork address translation
Network address translationVarsha Honde
 
Inter Process Communication
Inter Process CommunicationInter Process Communication
Inter Process CommunicationAdeel Rasheed
 
Hardware multithreading
Hardware multithreadingHardware multithreading
Hardware multithreadingFraboni Ec
 
Security problems in TCP/IP
Security problems in TCP/IPSecurity problems in TCP/IP
Security problems in TCP/IPSukh Sandhu
 
Cryptography and Message Authentication NS3
Cryptography and Message Authentication NS3Cryptography and Message Authentication NS3
Cryptography and Message Authentication NS3koolkampus
 

Was ist angesagt? (20)

Transmission Control Protocol (TCP)
Transmission Control Protocol (TCP)Transmission Control Protocol (TCP)
Transmission Control Protocol (TCP)
 
Transport layer services
Transport layer servicesTransport layer services
Transport layer services
 
Socket programming in python
Socket programming in pythonSocket programming in python
Socket programming in python
 
Ppt of routing protocols
Ppt of routing protocolsPpt of routing protocols
Ppt of routing protocols
 
Socket programming or network programming
Socket programming or network programmingSocket programming or network programming
Socket programming or network programming
 
Run time storage
Run time storageRun time storage
Run time storage
 
Pipes in Windows and Linux.
Pipes in Windows and Linux.Pipes in Windows and Linux.
Pipes in Windows and Linux.
 
One Time Pad Encryption Technique
One Time Pad Encryption TechniqueOne Time Pad Encryption Technique
One Time Pad Encryption Technique
 
IP Addressing and Subnetting
IP Addressing and SubnettingIP Addressing and Subnetting
IP Addressing and Subnetting
 
IPv4 Addressing
 IPv4 Addressing   IPv4 Addressing
IPv4 Addressing
 
IPv4
IPv4IPv4
IPv4
 
Network address translation
Network address translationNetwork address translation
Network address translation
 
Addressing sequencing
Addressing sequencingAddressing sequencing
Addressing sequencing
 
Cn ipv4 addressing
Cn ipv4 addressingCn ipv4 addressing
Cn ipv4 addressing
 
Inter Process Communication
Inter Process CommunicationInter Process Communication
Inter Process Communication
 
IP Multicasting
IP MulticastingIP Multicasting
IP Multicasting
 
Transport layer
Transport layer Transport layer
Transport layer
 
Hardware multithreading
Hardware multithreadingHardware multithreading
Hardware multithreading
 
Security problems in TCP/IP
Security problems in TCP/IPSecurity problems in TCP/IP
Security problems in TCP/IP
 
Cryptography and Message Authentication NS3
Cryptography and Message Authentication NS3Cryptography and Message Authentication NS3
Cryptography and Message Authentication NS3
 

Ähnlich wie Socket programming

Introduction to sockets tcp ip protocol.ppt
Introduction to sockets tcp ip protocol.pptIntroduction to sockets tcp ip protocol.ppt
Introduction to sockets tcp ip protocol.pptMajedAboubennah
 
Socket programming in C
Socket programming in CSocket programming in C
Socket programming in CDeepak Swain
 
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.pptINTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.pptsenthilnathans25
 
Sockets in unix
Sockets in unixSockets in unix
Sockets in unixswtjerin4u
 
Socket programming-tutorial-sk
Socket programming-tutorial-skSocket programming-tutorial-sk
Socket programming-tutorial-sksureshkarthick37
 
Application Layer and Socket Programming
Application Layer and Socket ProgrammingApplication Layer and Socket Programming
Application Layer and Socket Programmingelliando dias
 
Network programming using python
Network programming using pythonNetwork programming using python
Network programming using pythonAli Nezhad
 
Socket Programming Intro.pptx
Socket  Programming Intro.pptxSocket  Programming Intro.pptx
Socket Programming Intro.pptxssuserc4a497
 
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونیاسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونیMohammad Reza Kamalifard
 
Socket programming
Socket programmingSocket programming
Socket programmingUjjwal Kumar
 

Ähnlich wie Socket programming (20)

L5-Sockets.pptx
L5-Sockets.pptxL5-Sockets.pptx
L5-Sockets.pptx
 
Introduction to sockets tcp ip protocol.ppt
Introduction to sockets tcp ip protocol.pptIntroduction to sockets tcp ip protocol.ppt
Introduction to sockets tcp ip protocol.ppt
 
Sockets
Sockets Sockets
Sockets
 
Socket programming in C
Socket programming in CSocket programming in C
Socket programming in C
 
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.pptINTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
 
Basic socket programming
Basic socket programmingBasic socket programming
Basic socket programming
 
sockets_intro.ppt
sockets_intro.pptsockets_intro.ppt
sockets_intro.ppt
 
Sockets intro
Sockets introSockets intro
Sockets intro
 
Sockets in unix
Sockets in unixSockets in unix
Sockets in unix
 
Socket programming-tutorial-sk
Socket programming-tutorial-skSocket programming-tutorial-sk
Socket programming-tutorial-sk
 
123
123123
123
 
Application Layer and Socket Programming
Application Layer and Socket ProgrammingApplication Layer and Socket Programming
Application Layer and Socket Programming
 
Basics of sockets
Basics of socketsBasics of sockets
Basics of sockets
 
Network programming using python
Network programming using pythonNetwork programming using python
Network programming using python
 
Pemrograman Jaringan
Pemrograman JaringanPemrograman Jaringan
Pemrograman Jaringan
 
Socket Programming Intro.pptx
Socket  Programming Intro.pptxSocket  Programming Intro.pptx
Socket Programming Intro.pptx
 
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونیاسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
sockets
socketssockets
sockets
 

Kürzlich hochgeladen

ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdfssuserdda66b
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseAnaAcapella
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 

Kürzlich hochgeladen (20)

ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 

Socket programming

  • 2. Contents • Socket • Socket Structures • Socket Functions • TCP Example – TCP Client – TCP Server • UDP Example – UDP Client – UDP Server • Functions for Multicasting
  • 3. Socket • Socket – Source ( IP , Port ) – Destination ( IP , Port ) – Protocol ( TCP , UDP , SCTP) • Connection Oriented / Connection less
  • 4. Socket Structures • sockaddr • sockaddr_in – Connection information. Used by connect , send , recv etc • in_addr – IP address in long format • hostent – The IP addresses of a hostname. Used by gethostbyname()
  • 7. Socket Functions TCP UDP socket bind listen accept connect write /send read / recv socket bind sendto recvfrom
  • 8. Socket Functions socket: creates a socket of a given domain, type, protocol (buy a phone) bind: assigns a name to the socket (get a telephone number) listen: specifies the number of pending connections that can be queued for a server socket. (call waiting allowed) accept: server accepts a connection request from a client (answer phone) connect: client requests a connection request to a server (call) send, sendto: write to connection (speak) recv, recvfrom: read from connection (listen) shutdown: end the call
  • 11. Socket Functions • Supporting Functions – For Port Numbers • htons / htonl – Host to Network Byte Order (short-16/long-32) • ntohs/ntohl – Network to Host Byte Order (short-16/long-32) – For IP Address • inet_ntoa – convert an IP address to dotted format • inet_addr – convert an IP address to a long format – For Host • gethostbyname
  • 12. Socket Functions • Supporting functions Example – htons & inet_addr • struct sockaddr_in server; • server.sin_port = htons( 80 ); • server.sin_addr.s_addr = inet_addr("74.125.235.20");
  • 13. socket() • int socket (int domain , int type , int protocol) – domain (Address Family) • AF_INET (IP version 4) • AF_INET6 (IP version 6) – Type : • SOCK_STREAM (connection oriented TCP protocol) • SOCK_DGRAM (connectionless UDP protocol) – Protocol : • 0 , (zero) to detect protocol according to the type • IPPROTO_TCP – returns Socket Descriptor on success
  • 15. bind() • int bind(int sid , struct sockaddr *addrptr , int len) – sid : • socket ID obtained through socket() – *addrptr: (for local host) • Family dependent address • Used to bind IP and Port number to a socket – len • Length of the addrptr
  • 17. listen() • int listen(int sid , int size) – sid: • Socket descriptor obtained through socket() – size: • Number of connections that can be handled concurrently – returns 0 on success or -1 in failure – Example • listen ( socket_desc , 5 );
  • 18. connect() • int connect(int sid , struct sockaddr *addrptr , int len) – sid : • socket ID obtained through socket() – *addrptr: (for remote host or Destination) • Family dependent address • Used to specify destination (IP and Port) – len • Length of the addrptr – returns 0 on success and -1 on failure
  • 20. accept() • int accept(int sid , struct sockaddr *addrptr , int len) – sid : • socket ID obtained through socket() – *addrptr: ( remote host who requested to connect) • Family dependent address • Used to get remote client address (IP and Port) – len • Length of the addrptr – returns new sock descriptor and address of a remote client who requested the connection by connect()
  • 21.
  • 22. send() / recv() • int send (int sid , const char *buffer, int len , int flag) • Int recv (int sid , const char *buffer, int len , int flag) • int sendto (int sid , const char *buffer, int len , int flag struct sockaddr *addrptr, int addrptr_len) • int recvfrom (int sid , const char *buffer, int len ,int flag struct sockaddr *addrptr, int addrptr_len)
  • 23. Getting IP of a host name/domain • struct hostent * gethostbyname()
  • 24.
  • 25. Functions for UDP communication • int sendto – int sid – const char *buffer, int len , int flag – struct sockaddr *addrptr, int addrptr_len • int recvfrom – int sid , – const char *buffer, int len , int flag – struct sockaddr *addrptr, int addrptr_len
  • 26. UDP Receiver sd=socket(AF_INET, SOCK_DGRAM, 0); servAddr.sin_family = AF_INET; servAddr.sin_addr.s_addr = htonl(INADDR_ANY); servAddr.sin_port = htons(SERVER_PORT); rc = bind (sd,(struct sockaddr *)&servAddr, sizeof(servAddr)); n = recvfrom(sd, msg, MAX_MSG, 0,(struct sockaddr *)&cliAddr , sizeof(cliAddr)
  • 27. UDP sender sd = socket(AF_INET,SOCK_DGRAM,0); remoteServAddr.sin_family = AF_INET; remoteServAddr.sin_addr.s_addr = htonl(SERVER_IP); remoteServAddr.sin_port = htons(SERVER_PORT); rc = sendto(sd, msg, strlen(msg)+1, 0, (struct sockaddr *) &remoteServAddr, sizeof(remoteServAddr));
  • 28. Functions for Multicasting • int getsockopt( – int sid, – int level, int optname, void* optval, – int* optlen); • int setsockopt( – int sid, – int level, int optname, const void* optval, – int optlen); • int IN_MULTICAST(ntohl(Addr.sin_addr.s_addr))
  • 29. Multicasting – Function Arguments • Socket ID – AF_INET – SOCK_DGRAM or SOCK_RAW • Level (identifies the layer that is to handle the option, message or query) – SOL_SOCKET (socket layer) – IPPROTO_IP (IP layer)
  • 30. Multicasting – Function Arguments • optname (option for multicasting) setsockopt() getsockopt() IP_MULTICAST_LOOP yes yes IP_MULTICAST_TTL yes yes IP_MULTICAST_IF yes yes IP_ADD_MEMBERSHIP yes no IP_DROP_MEMBERSHIP yes no
  • 31. Options Value for Multicasting • loopback – u_char loop; // loop = 0 or 1 – setsockopt(socket, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop)); • TTL – u_char ttl; // default = 1 for own network only, 0 to 255 – setsockopt(socket, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)); • Interface (multicast datagram sent from) – struct in_addr interface_addr; – setsockopt (socket, IPPROTO_IP, IP_MULTICAST_IF, &interface_addr, sizeof(interface_addr));
  • 32. Options Value for Multicasting • Membership request structure struct ip_mreq { /* IP multicast address of group */ struct in_addr imr_multiaddr; /* local IP address of interface */ struct in_addr imr_interface; }; • Add Members – struct ip_mreq mreq; – setsockopt (socket, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)); • Drop Members – struct ip_mreq mreq; – setsockopt (socket, IPPROTO_IP, IP_DROP_MEMBERSHIP, &mreq, sizeof(mreq));
  • 33. Multicast Receiver sd = socket(AF_INET,SOCK_DGRAM,0); servAddr.sin_family=AF_INET; servAddr.sin_addr.s_addr=htonl(INADDR_ANY); servAddr.sin_port=htons(SERVER_PORT); rc = bind(sd,(struct sockaddr *) &servAddr, sizeof(servAddr)) /* join multicast group */ mreq.imr_multiaddr.s_addr=mcastAddr.s_addr; mreq.imr_interface.s_addr=htonl(INADDR_ANY); rc = setsockopt(sd,IPPROTO_IP,IP_ADD_MEMBERSHIP,(void *) &mreq, sizeof(mreq)); n = recvfrom(sd,msg,MAX_MSG,0,(struct sockaddr *) &cliAddr,&cliLen);
  • 34. Multicast Sender //simple UDP sender sd = socket(AF_INET,SOCK_DGRAM,0); setsockopt(sd,IPPROTO_IP,IP_MULTICAST_TTL, &ttl,sizeof(ttl) servAddr.sin_family = AF_INET; servAddr.sin_addr.s_addr = htonl(SERVER_IP); servAddr.sin_port = htons(SERVER_PORT); rc = sendto(sd,argv[i],strlen(argv[i])+1,0, (struct sockaddr *) &servAddr, sizeof(servAddr));