Server Code
------------------------------------------------------------------------------
**************************************************************************
Client Code
-------------------------------------------------------
OUTPUT
------------------------
Open two terminal
First terminal
-------------------------
Second terminal
---------------------------------------
------------------------------------------------------------------------------
#include
#include
#include //inet_addr
//#include //write
int main(int argc , char *argv[])
{
int socket_desc , client_sock , c;
struct sockaddr_in server_addr , client;
//Create socket
socket_desc = socket(AF_INET , SOCK_STREAM , 0);
if (socket_desc == -1)
{
printf("Could not create socket");
}
puts("Socket created");
//Prepare the socket address_in structure
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons( 9999 );
//Bind
if( bind(socket_desc,(struct sockaddr *)&server_addr , sizeof(server_addr)) < 0)
{
//print the error message
perror("bind failed. Error");
return 1;
}
puts("bind done");
//Listen
listen(socket_desc , 3);
//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
//accept connection from an incoming client
client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c);
if (client_sock < 0)
{
perror("accept failed");
return 1;
}
puts("Connection accepted");
return 0;
}
**************************************************************************
Client Code
-------------------------------------------------------
#include //printf,scanf
#include //socket
#include //inet_addr
int main(int argc , char *argv[])
{
int sock;
struct sockaddr_in server_addr;
//Create socket
sock = socket(AF_INET , SOCK_STREAM , 0);
if (sock == -1)
{
printf("Could not create socket");
}
puts("Socket created");
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons( 9999 );
//Connect to remote server
if (connect(sock , (struct sockaddr *)&server_addr , sizeof(server_addr)) < 0)
{
perror("connect failed. Error");
return 1;
}
puts("Connected\n");
return 0;
}
***************************************************************************OUTPUT
------------------------
Open two terminal
First terminal
-------------------------
gcc server3.c && ./a.out
Second terminal
---------------------------------------
gcc client3.c && ./a.out
0 Comments:
Post a Comment