title: Socket program gives "Transport endpoint is already connected" error
body: <p>I am trying to create a very simple client-server chat program, where two programs can communicate with each other. However, the accept function is giving me the error "invalid argument". I am pasting the code here:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;sys/socket.h&gt;
  #include &lt;netinet/in.h&gt;
  #include &lt;string.h&gt;
  #include &lt;fcntl.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;errno.h&gt;
  
  int main()
  {
  
  struct sockaddr_in myaddr;
  struct sockaddr_in otheraddr;
  int sockid;
  int bindid;
  int recvsockid;
  int clientlen;
  int connectid;
  
  char send_msg[100] = "Program 1", recv_msg[100];
  int recvid, sendid;
  int myport_id = 4550;
  int otherport_id = 4560;
  
  sockid = socket(AF_INET, SOCK_STREAM, 0);
  //fcntl(sockid, F_SETFL, O_NONBLOCK);
  
  if (sockid &lt; 0)
  {
      printf("\nCould not create socket");
  }
  
  bzero((char*)&amp;myaddr, sizeof(struct sockaddr_in));
  myaddr.sin_family = AF_INET;
  myaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
  myaddr.sin_port = htons(myport_id);
  
  bzero((char*)&amp;otheraddr, sizeof(struct sockaddr_in));
  otheraddr.sin_family = AF_INET;
  otheraddr.sin_addr.s_addr = inet_addr("127.0.0.1");
  otheraddr.sin_port = htons(otherport_id);
  
  
  bindid = bind(sockid, (struct sockaddr*)&amp;myaddr, sizeof(struct sockaddr_in));
  if(bindid &lt; 0)
      printf("bind error \n");
  
  listen(bindid, 5);
  
  do
  {
      connectid = connect(sockid, (struct sockaddr*)&amp;otheraddr, sizeof(struct sockaddr_in));
  if (connectid &lt; 0 &amp;&amp; !(errno == EINPROGRESS))
  {
      //printf("%s", strerror(errno));
      perror("connect");
      exit(1);
  }
      recvsockid = accept(sockid, (struct sockaddr*)&amp;myaddr, &amp;clientlen);
  if (recvsockid &lt; 0 &amp;&amp; !(errno == EINPROGRESS || errno == EAGAIN))
  {
      perror("accept");
      exit(1);
  }
  } while (connectid &lt; 0 &amp;&amp; recvsockid &lt; 0);
  
  do
  {
      gets(send_msg);
      sendid = sendto(sockid, send_msg, 100, 0, (struct sockaddr*)&amp;otheraddr, sizeof(struct sockaddr_in));
      fprintf(stderr, "%d", sendid);
      if(sendid &lt; 0)
          printf("error3\n");
  
      recvid = recvfrom(recvsockid, recv_msg, 100, 0, (struct sockaddr*)&amp;myaddr, &amp;clientlen);
      if (recvid &lt; 0)
      {
          printf("\nError in receive");
          break;
      }
  
  } while (1);
  
  return 0;
  }
  </code></pre>
  
  <p>I will be grateful if someone could tell me why I am getting this error, and how to correct it.</p>
  
  <p>Thanks a lot.</p>