title: Socket Programming in C(Client Server Example)
body: <p>I am completely new to programming in unix and have written the following code for client and server programming. When I try to run the client code it says "Connection refused". Could somebody please tell me what could be the reason of it. </p>
  
  <p>Server Code : </p>
  
  <pre><code>#include&lt;stdio.h&gt;
  #include&lt;stdlib.h&gt;
  #include&lt;sys/types.h&gt;
  #include&lt;sys/socket.h&gt;
  #include &lt;errno.h&gt;
  #include&lt;string.h&gt;
  #include &lt;netinet/in.h&gt;
  #include &lt;arpa/inet.h&gt;
  
  int main(void)
  {
      int sockid,newsockid;
      socklen_t addr_size;
      char *msg="What a beautiful morning!";
      int len, bytes_sent;
      sockid=socket(AF_INET,SOCK_STREAM,0);
      if(sockid==-1)
      {
          perror("socket");
          exit(1);
      }
      else
          printf("created");
      struct sockaddr_in serveraddr,clientaddr;
      bzero((char *)&amp;serveraddr,sizeof(serveraddr));
      serveraddr.sin_family=AF_INET;
      serveraddr.sin_port=htons(7400);
      serveraddr.sin_addr.s_addr=INADDR_ANY;
  
      if(bind(sockid,(struct sockaddr *)&amp;serveraddr,sizeof(serveraddr))&lt;0)
      {
          perror("bind");
          return -1;
      }
  
      listen(sockid,5);
      addr_size=sizeof(clientaddr);
      newsockid=accept(sockid,(struct sockaddr *)&amp;clientaddr,&amp;addr_size);
      len = strlen(msg);
      bytes_sent = send(sockid, msg, len, 0);
      close(sockid);
  }
  </code></pre>
  
  <p>Client Code : </p>
  
  <pre><code>#include&lt;stdio.h&gt;
  #include&lt;stdlib.h&gt;
  #include&lt;sys/types.h&gt;
  #include&lt;sys/socket.h&gt;
  #include &lt;errno.h&gt;
  #include&lt;string.h&gt;
  #include &lt;netinet/in.h&gt;
  #include &lt;arpa/inet.h&gt;
  
  int main(void)
  {
      int byte_count;
      struct sockaddr_in serveraddr;
      char *servername;
      char buf[256];
      socklen_t addr_size;
      int sockfd;
  
      sockfd=socket(AF_INET,SOCK_STREAM,0);
      bzero(&amp;serveraddr,sizeof(serveraddr));
      serveraddr.sin_family=AF_INET;
      serveraddr.sin_port=htons(11378);
      servername=gethostbyname("localhost");
      inet_pton(AF_INET,servername,&amp;serveraddr.sin_addr);
  
      addr_size=sizeof(serveraddr);
      if(connect(sockfd,(struct sockaddr *)&amp;serveraddr,addr_size)==-1)
      {
          perror("connect");
          exit(1);
      }
  
      byte_count = recv(sockfd, buf, sizeof buf, 0);
      printf("recv()'d %d bytes of data in buf\n", byte_count);
  
      close(sockfd);
  }
  </code></pre>
  
  <p>An early help would be appreciated.
  Thanks.</p>