0% found this document useful (0 votes)
9 views3 pages

Program Server

The document contains C code for a simple TCP server and client. The server listens on port 8001 and accepts connections, while the client connects to the server and sends a message. Both programs include error handling for socket creation, binding, listening, and connecting.

Uploaded by

foreverbo089
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views3 pages

Program Server

The document contains C code for a simple TCP server and client. The server listens on port 8001 and accepts connections, while the client connects to the server and sends a message. Both programs include error handling for socket creation, binding, listening, and connecting.

Uploaded by

foreverbo089
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

PROGRAM

SERVER

#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
void main()
{
int ssock,cfd,len;
char msg[200];
ssock=socket(AF_INET,SOCK_STREAM,0);
if(ssock<0)
printf("Socket error\n");
else
printf("Socket Success\n");
struct sockaddr_in servaddr;
len=sizeof(servaddr);
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(8001);
servaddr.sin_addr.s_addr=inet_addr("127.0.0.1");
if(bind(ssock,(struct sockaddr *)&servaddr,sizeof(servaddr))<0)
{
printf("Bind error\n");
exit(0);
}
printf("Bind success\n");

if(listen(ssock,5)<0)
{
printf("Listen error\n");
exit(0);
}
printf("Listen Success\n");
cfd=accept(ssock,(struct sockaddr *)&servaddr,&len);
if(cfd<0)
{
printf("Accept error\n");
exit(0);
}
printf("Accept Success\n");

bzero(msg,200);
recv(cfd,msg,sizeof(msg),0);
printf("%s",msg);
close(cfd);close(ssock);
}

CLIENT

#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>

void main()
{
int csock;
char msg[200];
csock=socket(AF_INET,SOCK_STREAM,0);
if(csock<0)
printf("Socket error\n");
else
printf("Socket Success\n");
struct sockaddr_in servaddr;
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(8001);
servaddr.sin_addr.s_addr=inet_addr("127.0.0.1");
if(connect(csock,(struct sockaddr *)&servaddr,sizeof(servaddr))<0)
{
printf("connect error\n");
exit(0);
}
printf("connect Success\n");

bzero(msg,200);
printf("msg to server:\n");
fgets(msg,sizeof(msg),stdin);
send(csock,msg,sizeof(msg),0);
close(csock);
}

OUTPUT

SERVER

CLIENT

You might also like