Unix Networking: Client
26 Nov 2012The following snippet outlines the skeleton of a client socket application. It’s the bare bones of what is needed to establish the client connection.
int sockfd, numbytes;
char buf[MAXDATASIZE];
struct addrinfo hints, *servinfo, *p;
int rv;
char s[INET6_ADDRSTRLEN];
/* fill out the address info */
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
/* create the actual server address */
getaddrinfo("www.remoteplace.com", PORT, &hints, &servinfo);
/* create the socket file descriptor */
sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
/* perform the network connect */
connect(sockfd, p->ai_addr, p->ai_addrlen);
/* free up the addres structure */
freeaddrinfo(servinfo);
/* receive some data on the socket */
recv(sockfd, buf, MAXDATASIZE-1, 0));
/* close the socket off */
close(sockfd);
###Further reading The getaddrinfo system call The socket system call The connect system call The recv system call The send system call