Coder's Guild Mailing List

Re: C sockets

Posted by Steve Hawkinson on 1999-05-21

Here is some code that I have used on Linux.

int sock=call_socket("localhost",(unsigned short) 6060);

int call_socket(char *hostname, unsigned short portnum)
{ struct sockaddr_in sa;
 struct hostent     *hp;
 int s;

 if ((hp= gethostbyname(hostname)) == NULL) { /* do we know the host's */
   errno= ECONNREFUSED;                       /* address? */
   return(-1);                                /* no */
 }

 memset(&sa,0,sizeof(sa));
 memcpy((char *)&sa.sin_addr,hp->h_addr,hp->h_length);     /* set address */
 sa.sin_family= AF_INET;      //hp->h_addrtype;
 sa.sin_port= htons((u_short)portnum);

 if ((s= socket(hp->h_addrtype,SOCK_STREAM,0)) < 0)     /* get socket */
   return(-1);
 if (connect(s,(struct sockaddr *)&sa,sizeof sa) < 0) { /* connect */
   close(s);
   return(-1);
 }
 return(s);
}

void send_message(char* msg){
  if(sock==-1){
      sock=call_socket("localhost",6060);
  }
  send(sock,msg,strlen(msg),0);
}

int read_message(char *buf, /* pointer to the buffer */
              int n      /* number of characters (bytes) we want */
              ){
  int bcount; /* counts bytes read */
  int br;     /* bytes read this pass */

  bcount= 0;
  br= 0;
  while (bcount < n) {             /* loop until full buffer */
    if ((br= read(sock,buf,n-bcount)) > 0) {
      bcount += br;                /* increment byte counter */
      buf += br;                   /* move buffer ptr for next read */
    }
    else if (br < 0)               /* signal an error to the caller */
      return(-1);
  }
  return(bcount);
}

> Could anybody please explain me how to create a TCP socket and send/receive
> data in C? I'm absolutely stuck. (I'm using FreeBSD by the way.) Thx in
> advance!

I think you should get something out of this code.  I think it should 
work in FreeBSD, the man page for socket says that it is a BSD function.  
    
Steve Hawkinson