SlideShare une entreprise Scribd logo
1  sur  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));

Contenu connexe

Tendances

Internet control message protocol
Internet control message protocolInternet control message protocol
Internet control message protocolasimnawaz54
 
TCP - Transmission Control Protocol
TCP - Transmission Control ProtocolTCP - Transmission Control Protocol
TCP - Transmission Control ProtocolPeter R. Egli
 
Address resolution protocol (ARP)
Address resolution protocol (ARP)Address resolution protocol (ARP)
Address resolution protocol (ARP)NetProtocol Xpert
 
Classless inter domain routing
Classless inter domain routingClassless inter domain routing
Classless inter domain routingVikash Gangwar
 
Open shortest path first (ospf)
Open shortest path first (ospf)Open shortest path first (ospf)
Open shortest path first (ospf)Respa Peter
 
Socket programming
Socket programmingSocket programming
Socket programmingMdEmonRana
 
Ip addressing
Ip addressingIp addressing
Ip addressingsid1322
 
Socket programming or network programming
Socket programming or network programmingSocket programming or network programming
Socket programming or network programmingMmanan91
 
Unicasting , Broadcasting And Multicasting New
Unicasting , Broadcasting And Multicasting NewUnicasting , Broadcasting And Multicasting New
Unicasting , Broadcasting And Multicasting Newtechbed
 

Tendances (20)

Tcp
TcpTcp
Tcp
 
Internet control message protocol
Internet control message protocolInternet control message protocol
Internet control message protocol
 
Sub Netting
Sub NettingSub Netting
Sub Netting
 
TCP - Transmission Control Protocol
TCP - Transmission Control ProtocolTCP - Transmission Control Protocol
TCP - Transmission Control Protocol
 
Address resolution protocol (ARP)
Address resolution protocol (ARP)Address resolution protocol (ARP)
Address resolution protocol (ARP)
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
Basic socket programming
Basic socket programmingBasic socket programming
Basic socket programming
 
Icmp
IcmpIcmp
Icmp
 
Classless inter domain routing
Classless inter domain routingClassless inter domain routing
Classless inter domain routing
 
Open shortest path first (ospf)
Open shortest path first (ospf)Open shortest path first (ospf)
Open shortest path first (ospf)
 
TCP Vs UDP
TCP Vs UDP TCP Vs UDP
TCP Vs UDP
 
5. icmp
5. icmp5. icmp
5. icmp
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Subnetting
SubnettingSubnetting
Subnetting
 
Sockets
Sockets Sockets
Sockets
 
Ip addressing classful
Ip addressing classfulIp addressing classful
Ip addressing classful
 
Socket programming
Socket programming Socket programming
Socket programming
 
Ip addressing
Ip addressingIp addressing
Ip addressing
 
Socket programming or network programming
Socket programming or network programmingSocket programming or network programming
Socket programming or network programming
 
Unicasting , Broadcasting And Multicasting New
Unicasting , Broadcasting And Multicasting NewUnicasting , Broadcasting And Multicasting New
Unicasting , Broadcasting And Multicasting New
 

Similaire à 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
 
session6-Network Programming.pptx
session6-Network Programming.pptxsession6-Network Programming.pptx
session6-Network Programming.pptxSrinivasanG52
 
TCP IP
TCP IPTCP IP
TCP IPhivasu
 

Similaire à 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
 
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
 
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
 
sockets
socketssockets
sockets
 
session6-Network Programming.pptx
session6-Network Programming.pptxsession6-Network Programming.pptx
session6-Network Programming.pptx
 
Socket System Calls
Socket System CallsSocket System Calls
Socket System Calls
 
TCP IP
TCP IPTCP IP
TCP IP
 

Dernier

How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
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
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 

Dernier (20)

How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
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
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).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));