EmbLogic's Blog

Basic_program of socket

server_program

int main()
9 {
10 int s_sockfd,c_sockfd;
11 int c_len,s_len,s_result;
12 struct sockaddr_un s_address;
13 struct sockaddr_un c_address;
14 unlink(“emblogic”);
15 s_sockfd = socket(AF_UNIX,SOCK_STREAM,0);
16 printf(“Print the s_sockfd %d\n”,s_sockfd);
17 if(s_sockfd == -1)
18 {
19 perror(“Error due to fd\n”);
20 exit(EXIT_FAILURE);
21 }
22 s_address.sun_family = AF_UNIX;
23 strcpy(s_address.sun_path,”emblogic”);
24 s_len = sizeof(s_address);
25 bind(s_sockfd,(struct sockaddr*)&s_address,s_len);
26 listen(s_sockfd,5);
27 while(1)
28 {
29 char ch;
30 printf(“Server is waiting\n”);
31 c_len = sizeof(c_address);
32 c_sockfd = accept(s_sockfd,(struct sockaddr*)&c_address,&c_len);
33 if(c_sockfd == -1)
34 {
35 perror(“Error due the accept call\n”);
36 exit(EXIT_FAILURE);
37 }
38 read(c_sockfd,&ch,1);
39 printf(“Print the value of ch–>>%c\n”,ch);
40 ch++;
41 write(c_sockfd,&ch,1);
42 close(c_sockfd);
43 }
44 return 0;
45 }

client_program

1 #include<stdio.h>
2 #include<stdlib.h>
3 #include<string.h>
4 #include<sys/types.h>
5 #include<unistd.h>
6 #include<sys/un.h>
7 #include<sys/socket.h>
8 int main()
9 {
10 int sockfd;
11 int len,result;
12 struct sockaddr_un address;
13 char ch = ‘A’;
14 sockfd = socket(AF_UNIX,SOCK_STREAM,0);
15 printf(“Print the client sockfd–>>>%d\n”,sockfd);
16 if(sockfd < 0)
17 {
18 perror(“Error due the sockfd\n”);
19 exit(EXIT_FAILURE);
20 }
21 address.sun_family = AF_UNIX;
22 strcpy(address.sun_path,”emblogic”);
23 len = sizeof(address);
24 result = connect(sockfd,(struct sockaddr*)&address,len);
25 if(result == -1)
26 {
27 perror(“Error due the client1\n”);
28 exit(EXIT_FAILURE);
29 }
30 write(sockfd,&ch,1);
31 read(sockfd,&ch,1);
32 printf(“Char in server=%c\n”,ch);
33 close(sockfd);
34 return 0;
35 }
~

 

 

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>