codice:
/* mysocketfn.h */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#define BUF_MAX 1000
void send_message(char*addressname, int port, char*message_to_send)
{
struct hostent *hs;
struct sockaddr_in serveraddr;
fprintf(stdout,"Retrieving information about %s\n",addressname);
//resolve hostname
hs = gethostbyname(addressname);
if (hs == NULL) // do some error checking
{
fprintf(stdout,"Errore gethostbyname(%s)",addressname);
herror("gethostbyname");
exit(1);
}
// print information about this host:
fprintf(stdout,"Official name is: %s\n", hs->h_name);
fprintf(stdout,"IP address: %s\n", inet_ntoa(*(struct in_addr*)hs->h_addr));
unsigned long ula = *((unsigned long *)hs->h_addr_list[0]);
fprintf(stdout, "gethostbyname(%s) result: %lu\n",addressname, ula);
// Configure settings of the server address struct
// Set IP address
serveraddr.sin_addr.s_addr=ula;
// Address family = Internet
serveraddr.sin_family = AF_INET;
// Set port number, using htons function to use proper byte order
serveraddr.sin_port = htons(port);
memset(&serveraddr.sin_zero, 0, sizeof(serveraddr.sin_zero));
fprintf(stdout,"*Address in the correct form: %s\n",inet_ntoa(serveraddr.sin_addr));
//***********************************************************************************
//* CREATE SOCKET, CONNECT, SEND MESSAGE, RECEIVE RESPONSE, CLOSE SOCKET CONNECTION *
int sock; // socket descriptor
int chkerr;
char buff[BUF_MAX];
fprintf(stdout,"Creating socket...\n");
//Create socket descriptor
sock=socket(AF_INET,SOCK_STREAM,0);
if (sock < 0)
fprintf(stdout,"Error creating socket.\n");
else fprintf(stdout,"Socket created\n");
fprintf(stdout,"Connecting to %s on port %d...\n",inet_ntoa(serveraddr.sin_addr),port);
//Connect to server
chkerr=connect(sock,(struct sockaddr *)&serveraddr, sizeof(serveraddr));
if (chkerr<0)
fprintf(stdout,"Error connecting to the server\n");
else fprintf(stdout,"Connected to server\n");
fprintf(stdout,"Sending data...\n");
//Send data
fprintf(stdout,"Data:\n%s\n",message_to_send);
chkerr=send(sock,message_to_send,sizeof(message_to_send),0);
if (chkerr<0)
fprintf(stdout,"Data sending error\n");
else fprintf(stdout,"Data send\n");
fprintf(stdout,"Server response:\n\n");
//Receive response
memset(buff,0,sizeof(buff));
while((chkerr=recv(sock,buff,sizeof(buff),0)) != 0)
{
if (chkerr<0)
fprintf(stdout,"Data reception error\n");
else if (chkerr==0) fprintf(stdout,"End of data reception");
else fprintf(stdout,"%s",buff);
}
//CLOSE socket descriptor
close(sock);
fprintf(stdout,"Connection closed\n");
}