/* A simple client using TCP. Server name and port number are passed as an argument */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/uio.h>
#include <netinet/in.h>
#include <netdb.h>
#include <errno.h>
void error(const char *msg)
{
perror(msg);
exit(0);
}
int main(int argc, char *argv[])
{
int sockfd, portno, n;
struct sockaddr_in serv_addr; /*server adress*/
struct hostent *server; /*server name*/
struct iovec iov[1]; /*points to the segments of the (noncontiguous)outgoing message.*/
struct msghdr mh; /*contains parameter information for sendmsg.*/
char *string = "random string";
char primo[256];
strcpy(primo, string);
/* Specify the components of the message in an "iovec".*/
iov[0].iov_base = (caddr_t)primo;
iov[0].iov_len = sizeof(primo);
char buffer[256];
if (argc < 3) {
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]); /*port number*/
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
/* The message header contains parameters for sendmsg. */
mh.msg_name = (caddr_t) &server->h_addr;
mh.msg_namelen = sizeof(server->h_addr);
mh.msg_iov = iov;
mh.msg_iovlen = sizeof(iov);
printf("mh structure initialized \n");
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) {
error("ERROR connecting");
}
else printf("Connect() successful \n");
n = sendmsg(sockfd, &mh, 0); /* no flags used*/
if (n == -1) {
perror("sendmsg failed ");
strerror(errno);
return -1;
/* The output queue for a network interface was full. This gener‐
* ally indicates that the interface has stopped sending, but may
* be caused by transient congestion. (Normally, this does not
* occur in Linux. Packets are just silently dropped when a device
* queue overflows.) */
}
else printf("Sendmsg successfully executed \n");
bzero(buffer,256); /*azzera il buffer*/
n = read(sockfd,buffer,255);
if (n < 0)
error("ERROR reading from socket");
printf("%s\n",buffer);
close(sockfd);
return 0;
}