SlideShare una empresa de Scribd logo
1 de 5
Descargar para leer sin conexión
Internet socket programming using TCP/IP
The AF_INET sockets may be used by programs communicating across a TCP/IP network including
the Internet. The Windows Winsock interface also provides access to this socket domain.
SOCK_STREAM is a sequenced, reliable, connection-based two-way byte stream. For an AF_INET
domain socket, this is provided by default by a TCP connection that is established between the two
end points of the stream socket when it’s connected. Data may be passed in both directions along the
socket connection. The TCP protocols include facilities to fragment and reassemble long messages
and to retransmit any parts that may be lost in the network.
The protocol used for communication is usually determined by the socket type and domain. There is
normally no choice. The protocol parameter is used where there is a choice. 0 selects the default
protocol.
Socket Addresses
In the AF_INET domain, the address is specified using a structure called sockaddr_in, defined in
<netinet/in.h>, which contains at least these members:
struct sockaddr_in {
short int sin_family; /* AF_INET */
unsigned short int sin_port; /* Port number */
struct in_addr sin_addr; /* Internet address */
};
The IP address structure, in_addr, is defined as follows:
struct in_addr {
unsigned long int s_addr;
};
The underlying protocol, Internet Protocol (IP), which only has one address family, imposes a
particular way of specifying computers on a network. This is called the IP address. In IPV4, the four
bytes of an IP address constitute a single 32-bit value. An AF_INET socket is fully described by its
domain, IP address, and port number. From an application’s point of view, all sockets act like file
descriptors and are addressed by a unique integer value.
IPv6 uses a different socket domain, AF_INET6, and a different address format.
There may be several services available at the server computer. A client can address a particular
service on a networked machine by using an IP port. A port is identified within the system by
assigning a unique 16-bit integer and externally by the combination of IP address and port number.
The sockets are communication end points that must be bound to ports before communication is
possible.
If you want to allow the server to communicate with remote clients, you must specify a set of IP
addresses that you are willing to allow. You can use the special value, INADDR_ANY, to specify
that you’ll accept connections from all of the interfaces your computer may have. If you chose to,
you could distinguish between different network interfaces to separate, for example, internal Local
Area Network and external Wide Area Network connections. INADDR_ANY is a 32-bit integer
value that you can use in the sin_addr.s_addr field.
These functions convert 16-bit and 32-bit integers between native host format and the standard
network ordering. Their names are abbreviations for conversions — for example, “host to network,
long” (htonl) and “host to network, short” (htons). For computers where the native ordering is the
same as network ordering, these represent null operations.
To ensure correct byte ordering of the 16-bit port number, your server and client need to apply these
functions to the port address. The change to server3.c is server_address.sin_addr.s_addr =
htonl(INADDR_ANY);
server_address.sin_port = htons(9734);
You don’t need to convert the function call, inet_addr(“127.0.0.1”), because inet_addr is defined
to produce a result in network order. The change to client3.c is address.sin_port = htons(9734);
The server has also been changed to allow connections from any IP address by using
INADDR_ANY. of the address structure. However, you have a problem to resolve first.
Servers wait for connections on particular ports. Well-known services have allocated port numbers
that are used by all Linux and UNIX machines. These are usually, but not always, numbers less than
1024. Examples are the printer spooler (515), rlogin (513), ftp (21), and httpd (80). The last of these
is the standard port for web servers. Usually, port numbers less than 1024 are reserved for system
services and may only be served by processes with super user privileges. X/Open defines a constant
in netdb.h, IPPORT_RESERVED, to stand for the highest reserved port number.
Naming a Socket
AF_INET sockets are associated with an IP port number.
#include <sys/socket.h>
int bind(int socket, const struct sockaddr *address, size_t address_len);
The bind system call assigns the address specified in the parameter, address, to the unnamed
socket associated with the file descriptor socket. The length of the address structure is passed as
address_len. The length and format of the address depend on the address family. A particular address
structure pointer will need to be cast to the generic address type (struct sockaddr *) in the call to
bind.On successful completion, bind returns 0. If it fails, it returns -1 and sets errno.
Sample to solve Assignment2:
Write a C program using TCP/IP socket to send user data from client and server will receive
the data and concatenate that with user given data at server side and send it to client.
Client program:
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
int sockfd;
int len;
struct sockaddr_in address;
int result,l;
char msg[2048];
sockfd = socket(AF_INET, SOCK_STREAM, 0);
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr("127.0.0.1");
address.sin_port = 9734;
len = sizeof(address);
result = connect(sockfd, (struct sockaddr *)&address, len);
if(result == -1)
{
perror("oops: client1");
exit(1);
}
fgets(msg,200,stdin);
l=sizeof(msg);
write(sockfd, &msg, l);
read(sockfd, &msg, l);
printf("char from server = %sn", msg);
close(sockfd);
exit(0);
}
Creating socket:
sockfd = socket(AF_INET, SOCK_STREAM, 0);
This is same as file socket only the domain has been changed to AF_INET.
Socket Addresses
The client program used the sockaddr_in structure from the include file <netinet/in.h> to specify an
AF_INET address. It tries to connect to a server on the host with IP address 127.0.0.1. It uses a
function, inet_addr, to convert the text representation of an IP address into a form suitable for socket
addressing. The manual page for inet has more information on other address translation functions.
struct sockaddr_in
struct sockaddr_in {
u_char sin_len;
u_short sin_family; // Address family
u_short sin_port; // Port number
struct in_addr sin_addr; // Internet or IP address
char sin_zero[8]; // Same size as struct sockaddr
};
 The sin_family field is the address family (always AF_INET for TCP and UDP).
 The sin_port field is the port number, and the sin_addr field is the Internet address. The
sin_zero field is reserved, and you must set it to hexadecimal zeroes.
 Data type struct in_addr - this data type is used in certain contexts to contain an Internet host
address. It has just one field, named s_addr, which records the host address number as an
unsigned long int.
 sockaddr_in is a "specialized" sockaddr.
 sin_addr could be u_long.
 sin_addr is 4 bytes and 8 bytes are unused.
 sockaddr_in is used to specify an endpoint.
 The sin_port and sin_addr must be in Network Byte Order.
address.sin_family = AF_INET;
This stamen define that socket address is under AF_INET domain
address.sin_addr.s_addr = inet_addr("127.0.0.1");
This statement identifies the network.
Host Address Data Type - Data type for a host number.
 Internet host addresses are represented in some contexts as integers (type unsigned long int).
 In other contexts, the integer is packaged inside a structure of type struct in_addr. It would
be better if the usages were made consistent, but it is not hard to extract the integer from the
structure or put the integer into a structure.
 The following basic definitions for Internet addresses appear in the header file 'in.h'.
struct in_addr
 This data type is used in certain contexts to contain an Internet host address. It has just one
field, named s_addr, which records the host address number as an unsigned long int.
unsigned long int INADDR_LOOPBACK
 You can use this macro constant to stand for the ''address of this machine'' instead of finding
its actual address.
 It is the Internet address '127.0.0.1', which is usually called 'localhost'. This special constant
saves you the trouble of looking up the address of your own machine.
 Also, the system usually implements INADDR_LOOPBACK specially, avoiding any
network traffic for the case of one machine talking to itself.
unsigned long int INADDR_ANY
 You can use this macro constant to stand for ''any incoming address'' when binding to an
address. This is the usual address to give in the sin_addr member of struct sockaddr_in when
you want your server to accept Internet connections.
unsigned long int INADDR_BROADCAST
 This macro constant is the address you use to send a broadcast message.
 Likewise, by setting address.sin_addr.s_addr to INADDR_ANY, you are telling it to
automatically fill in the IP address of the machine the process is running on.
 INADDR_ANY is actually zero. For 0.0.0.0, it means any IP.
address.sin_port = 9734;
We have select port number 9734. This is an arbitrary choice that avoids the standard services (you
can’t use port numbers below 1024 because they are reserved for system use). Other port numbers
are often listed, with the services provided on them, in the system file /etc/services. When you’re
writing socket-based applications, always choose a port number not listed in this configuration file.
Connecting socket:
Connecting internet socket is same as file socket.
Now you can write anything from key board and do read operation as you have done in file
socket.
Server program:
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include<string.h>
int main()
{
int server_sockfd, client_sockfd;
int server_len,len,p;
struct sockaddr_in server_address;
struct sockaddr_in client_address;
server_sockfd = socket(AF_INET, SOCK_STREAM, 0);
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = inet_addr("127.0.0.1");
server_address.sin_port = 9734;
server_len = sizeof(server_address);
bind(server_sockfd, (struct sockaddr *)&server_address, server_len);
listen(server_sockfd, 5);
while(1) {
char msg[2048],msg1[2048];
printf("server waitingn");
len = sizeof(client_address);
client_sockfd = accept(server_sockfd,(struct sockaddr *)&client_address,&len);
read(client_sockfd, &msg, sizeof(msg));
fgets(msg1,2048,stdin);
strcat(msg,msg1);
p=sizeof(msg);
write(client_sockfd, &msg,p);
close(client_sockfd);
}
}

Más contenido relacionado

Más de Sisir Ghosh

ASP.NET Session 10
ASP.NET Session 10ASP.NET Session 10
ASP.NET Session 10Sisir Ghosh
 
ASP.NET Session 11 12
ASP.NET Session 11 12ASP.NET Session 11 12
ASP.NET Session 11 12Sisir Ghosh
 
ASP.NET Session 13 14
ASP.NET Session 13 14ASP.NET Session 13 14
ASP.NET Session 13 14Sisir Ghosh
 
ASP.NET Session 16
ASP.NET Session 16ASP.NET Session 16
ASP.NET Session 16Sisir Ghosh
 
ASP.NET System design 2
ASP.NET System design 2ASP.NET System design 2
ASP.NET System design 2Sisir Ghosh
 
ASP.NET Session 1
ASP.NET Session 1ASP.NET Session 1
ASP.NET Session 1Sisir Ghosh
 
Network security
Network securityNetwork security
Network securitySisir Ghosh
 
Module ii physical layer
Module ii physical layerModule ii physical layer
Module ii physical layerSisir Ghosh
 
Error detection and correction
Error detection and correctionError detection and correction
Error detection and correctionSisir Ghosh
 
Overview of data communication and networking
Overview of data communication and networkingOverview of data communication and networking
Overview of data communication and networkingSisir Ghosh
 
Application layer
Application layerApplication layer
Application layerSisir Ghosh
 

Más de Sisir Ghosh (13)

ASP.NET Session 10
ASP.NET Session 10ASP.NET Session 10
ASP.NET Session 10
 
ASP.NET Session 11 12
ASP.NET Session 11 12ASP.NET Session 11 12
ASP.NET Session 11 12
 
ASP.NET Session 13 14
ASP.NET Session 13 14ASP.NET Session 13 14
ASP.NET Session 13 14
 
ASP.NET Session 16
ASP.NET Session 16ASP.NET Session 16
ASP.NET Session 16
 
ASP.NET System design 2
ASP.NET System design 2ASP.NET System design 2
ASP.NET System design 2
 
ASP.NET Session 1
ASP.NET Session 1ASP.NET Session 1
ASP.NET Session 1
 
Transport layer
Transport layerTransport layer
Transport layer
 
Routing
RoutingRouting
Routing
 
Network security
Network securityNetwork security
Network security
 
Module ii physical layer
Module ii physical layerModule ii physical layer
Module ii physical layer
 
Error detection and correction
Error detection and correctionError detection and correction
Error detection and correction
 
Overview of data communication and networking
Overview of data communication and networkingOverview of data communication and networking
Overview of data communication and networking
 
Application layer
Application layerApplication layer
Application layer
 

Último

call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 

Último (20)

call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 

Internet socket programming using tcp assignment2

  • 1. Internet socket programming using TCP/IP The AF_INET sockets may be used by programs communicating across a TCP/IP network including the Internet. The Windows Winsock interface also provides access to this socket domain. SOCK_STREAM is a sequenced, reliable, connection-based two-way byte stream. For an AF_INET domain socket, this is provided by default by a TCP connection that is established between the two end points of the stream socket when it’s connected. Data may be passed in both directions along the socket connection. The TCP protocols include facilities to fragment and reassemble long messages and to retransmit any parts that may be lost in the network. The protocol used for communication is usually determined by the socket type and domain. There is normally no choice. The protocol parameter is used where there is a choice. 0 selects the default protocol. Socket Addresses In the AF_INET domain, the address is specified using a structure called sockaddr_in, defined in <netinet/in.h>, which contains at least these members: struct sockaddr_in { short int sin_family; /* AF_INET */ unsigned short int sin_port; /* Port number */ struct in_addr sin_addr; /* Internet address */ }; The IP address structure, in_addr, is defined as follows: struct in_addr { unsigned long int s_addr; }; The underlying protocol, Internet Protocol (IP), which only has one address family, imposes a particular way of specifying computers on a network. This is called the IP address. In IPV4, the four bytes of an IP address constitute a single 32-bit value. An AF_INET socket is fully described by its domain, IP address, and port number. From an application’s point of view, all sockets act like file descriptors and are addressed by a unique integer value. IPv6 uses a different socket domain, AF_INET6, and a different address format. There may be several services available at the server computer. A client can address a particular service on a networked machine by using an IP port. A port is identified within the system by assigning a unique 16-bit integer and externally by the combination of IP address and port number. The sockets are communication end points that must be bound to ports before communication is possible. If you want to allow the server to communicate with remote clients, you must specify a set of IP addresses that you are willing to allow. You can use the special value, INADDR_ANY, to specify that you’ll accept connections from all of the interfaces your computer may have. If you chose to, you could distinguish between different network interfaces to separate, for example, internal Local Area Network and external Wide Area Network connections. INADDR_ANY is a 32-bit integer value that you can use in the sin_addr.s_addr field. These functions convert 16-bit and 32-bit integers between native host format and the standard network ordering. Their names are abbreviations for conversions — for example, “host to network, long” (htonl) and “host to network, short” (htons). For computers where the native ordering is the same as network ordering, these represent null operations. To ensure correct byte ordering of the 16-bit port number, your server and client need to apply these functions to the port address. The change to server3.c is server_address.sin_addr.s_addr = htonl(INADDR_ANY);
  • 2. server_address.sin_port = htons(9734); You don’t need to convert the function call, inet_addr(“127.0.0.1”), because inet_addr is defined to produce a result in network order. The change to client3.c is address.sin_port = htons(9734); The server has also been changed to allow connections from any IP address by using INADDR_ANY. of the address structure. However, you have a problem to resolve first. Servers wait for connections on particular ports. Well-known services have allocated port numbers that are used by all Linux and UNIX machines. These are usually, but not always, numbers less than 1024. Examples are the printer spooler (515), rlogin (513), ftp (21), and httpd (80). The last of these is the standard port for web servers. Usually, port numbers less than 1024 are reserved for system services and may only be served by processes with super user privileges. X/Open defines a constant in netdb.h, IPPORT_RESERVED, to stand for the highest reserved port number. Naming a Socket AF_INET sockets are associated with an IP port number. #include <sys/socket.h> int bind(int socket, const struct sockaddr *address, size_t address_len); The bind system call assigns the address specified in the parameter, address, to the unnamed socket associated with the file descriptor socket. The length of the address structure is passed as address_len. The length and format of the address depend on the address family. A particular address structure pointer will need to be cast to the generic address type (struct sockaddr *) in the call to bind.On successful completion, bind returns 0. If it fails, it returns -1 and sets errno. Sample to solve Assignment2: Write a C program using TCP/IP socket to send user data from client and server will receive the data and concatenate that with user given data at server side and send it to client. Client program: #include <sys/types.h> #include <sys/socket.h> #include <stdio.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <stdlib.h> int main() { int sockfd; int len; struct sockaddr_in address; int result,l; char msg[2048]; sockfd = socket(AF_INET, SOCK_STREAM, 0); address.sin_family = AF_INET; address.sin_addr.s_addr = inet_addr("127.0.0.1"); address.sin_port = 9734; len = sizeof(address); result = connect(sockfd, (struct sockaddr *)&address, len); if(result == -1) { perror("oops: client1"); exit(1); } fgets(msg,200,stdin); l=sizeof(msg); write(sockfd, &msg, l);
  • 3. read(sockfd, &msg, l); printf("char from server = %sn", msg); close(sockfd); exit(0); } Creating socket: sockfd = socket(AF_INET, SOCK_STREAM, 0); This is same as file socket only the domain has been changed to AF_INET. Socket Addresses The client program used the sockaddr_in structure from the include file <netinet/in.h> to specify an AF_INET address. It tries to connect to a server on the host with IP address 127.0.0.1. It uses a function, inet_addr, to convert the text representation of an IP address into a form suitable for socket addressing. The manual page for inet has more information on other address translation functions. struct sockaddr_in struct sockaddr_in { u_char sin_len; u_short sin_family; // Address family u_short sin_port; // Port number struct in_addr sin_addr; // Internet or IP address char sin_zero[8]; // Same size as struct sockaddr };  The sin_family field is the address family (always AF_INET for TCP and UDP).  The sin_port field is the port number, and the sin_addr field is the Internet address. The sin_zero field is reserved, and you must set it to hexadecimal zeroes.  Data type struct in_addr - this data type is used in certain contexts to contain an Internet host address. It has just one field, named s_addr, which records the host address number as an unsigned long int.  sockaddr_in is a "specialized" sockaddr.  sin_addr could be u_long.  sin_addr is 4 bytes and 8 bytes are unused.  sockaddr_in is used to specify an endpoint.  The sin_port and sin_addr must be in Network Byte Order. address.sin_family = AF_INET; This stamen define that socket address is under AF_INET domain address.sin_addr.s_addr = inet_addr("127.0.0.1"); This statement identifies the network. Host Address Data Type - Data type for a host number.  Internet host addresses are represented in some contexts as integers (type unsigned long int).  In other contexts, the integer is packaged inside a structure of type struct in_addr. It would be better if the usages were made consistent, but it is not hard to extract the integer from the structure or put the integer into a structure.  The following basic definitions for Internet addresses appear in the header file 'in.h'. struct in_addr  This data type is used in certain contexts to contain an Internet host address. It has just one field, named s_addr, which records the host address number as an unsigned long int. unsigned long int INADDR_LOOPBACK
  • 4.  You can use this macro constant to stand for the ''address of this machine'' instead of finding its actual address.  It is the Internet address '127.0.0.1', which is usually called 'localhost'. This special constant saves you the trouble of looking up the address of your own machine.  Also, the system usually implements INADDR_LOOPBACK specially, avoiding any network traffic for the case of one machine talking to itself. unsigned long int INADDR_ANY  You can use this macro constant to stand for ''any incoming address'' when binding to an address. This is the usual address to give in the sin_addr member of struct sockaddr_in when you want your server to accept Internet connections. unsigned long int INADDR_BROADCAST  This macro constant is the address you use to send a broadcast message.  Likewise, by setting address.sin_addr.s_addr to INADDR_ANY, you are telling it to automatically fill in the IP address of the machine the process is running on.  INADDR_ANY is actually zero. For 0.0.0.0, it means any IP. address.sin_port = 9734; We have select port number 9734. This is an arbitrary choice that avoids the standard services (you can’t use port numbers below 1024 because they are reserved for system use). Other port numbers are often listed, with the services provided on them, in the system file /etc/services. When you’re writing socket-based applications, always choose a port number not listed in this configuration file. Connecting socket: Connecting internet socket is same as file socket. Now you can write anything from key board and do read operation as you have done in file socket. Server program: #include <sys/types.h> #include <sys/socket.h> #include <stdio.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <stdlib.h> #include<string.h> int main() { int server_sockfd, client_sockfd; int server_len,len,p; struct sockaddr_in server_address; struct sockaddr_in client_address; server_sockfd = socket(AF_INET, SOCK_STREAM, 0); server_address.sin_family = AF_INET; server_address.sin_addr.s_addr = inet_addr("127.0.0.1"); server_address.sin_port = 9734; server_len = sizeof(server_address); bind(server_sockfd, (struct sockaddr *)&server_address, server_len); listen(server_sockfd, 5); while(1) { char msg[2048],msg1[2048]; printf("server waitingn"); len = sizeof(client_address);
  • 5. client_sockfd = accept(server_sockfd,(struct sockaddr *)&client_address,&len); read(client_sockfd, &msg, sizeof(msg)); fgets(msg1,2048,stdin); strcat(msg,msg1); p=sizeof(msg); write(client_sockfd, &msg,p); close(client_sockfd); } }