EmbLogic's Blog

Basic program for socket_inet

SERVER

#include<stdio.h>
#include<stdlib.h>
#include<linux/types.h>
#include<linux/socket.h>
#include<sys/un.h>
#include<netinet/in.h>
int main(int argc,char *argv[])
{
int sfd,s_len,b,a,l,nfd,c_len,spn;
struct sockaddr_in addr;
struct sockaddr_in c_addr;
sfd = socket(AF_INET,SOCK_STREAM,0);
spn = atoi(argv[1]);//for command line arrguments
//int socket(int domain, int type, int protocol);3rd arrguments 0 for defalut 1 for udp and 2 for tcp;
if(sfd == -1)
{
perror(“Error due the sfd\n”);
exit(EXIT_FAILURE);
}
printf(“Print the socket fd–>>%d\n”,sfd);
addr.sin_family = AF_INET;
addr.sin_port = htons(spn);
addr.sin_addr.s_addr=htonl(INADDR_ANY);//chack man 7 ip
s_len = sizeof(addr);
b = bind(sfd, (struct sockaddr*)&addr,s_len);
//int bind(int sockfd, const struct sockaddr *addr,socklen_t addrlen);
if(b == -1)
{
perror(“Error due the bind call\n”);
exit(EXIT_FAILURE);
}
listen(sfd,6);
//int listen(int sockfd, int backlog); 2nd arrguments is depth of queue.
if(sfd == -1)
{
perror(“Error due the slisten call\n”);
exit(EXIT_FAILURE);
}
char ch[20];
c_len = sizeof(c_addr);
nfd = accept(sfd,(struct sockaddr*)&c_addr,&c_len);
printf(“hellow\n”);
// int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
if(a == -1)
{
perror(“Error due the accept call fail\n”);
exit(EXIT_FAILURE);
}
while(1)
{
read(nfd,&ch,20);
// ssize_t read(int fd, void *buf, size_t count);
printf(“Print the client word–>>%s\n”,ch);
}
close(nfd);
return 0;
}

CLIENT

int main(int argc,char *argv[])
9 {
10 int cfd,c_len,c,pn;
11 char ch[20];
12 pn = atoi(argv[2]);
13 struct sockaddr_in c_addr;
14 cfd = socket(AF_INET,SOCK_STREAM,0);
15 printf(“Print the cfd value —>>%d\n”,cfd);
16 if(cfd == -1)
17 {
18 perror(“Error due the socket call\n”);
19 exit(EXIT_FAILURE);
20 }
21 c_addr.sin_family = AF_INET;
22 c_addr.sin_port = htons(pn);
23 c_addr.sin_addr.s_addr =inet_addr(argv[1]);
24 c_len = sizeof(c_addr);
25 c = connect(cfd,(struct sockaddr*)&c_addr,c_len);
26 if(c == -1)
27 {
28 perror(“Error due the connect call fail\n”);
29 exit(EXIT_FAILURE);
30 }
31 while(1)
32 {
33 scanf(“%s”,ch);
34 write(cfd,&ch,20);
35 }
36 return 0;
37 }

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>