Giusto per far capire di cosa parlavo, posto qui anche le semplicissime applicazioni client e server.
codice:
client.cpp
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <strings.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#define MAXBUF 200
#define SERVPORT 7777
int main(int argc,char *argv[])
{
char buf[MAXBUF];
hostent* hp;
sockaddr_in sin;
int sock;
if (argc!=2)
{
fprintf(stderr,"usage: ./client host\n");
exit(1);
}
hp=gethostbyname(argv[1]);
if (!hp)
{
fprintf(stderr,"client: host sconosciuto\n");
exit(1);
}
bzero((char*)&sin,sizeof(sin));
sin.sin_family=AF_INET;
bcopy(hp->h_addr,(char*)&sin.sin_addr,hp->h_length);
sin.sin_port=htons(SERVPORT);
if ((sock=socket(PF_INET,SOCK_STREAM,0))<0)
{
perror("client: errore in socket");
exit(1);
}
if (connect(sock,(sockaddr*)&sin,sizeof(sin)) <0)
{
perror("client: errore in connect");
close(sock);
exit(1);
}
while (fgets(buf,sizeof(buf),stdin))
{
buf[MAXBUF-1]='\0';
send(sock,buf,strlen(buf)+1,0);
recv(sock,buf,sizeof(buf),0);
fputs(buf,stdout);
}
return 0;
}
codice:
server.cpp
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <strings.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#define MAXCONN 10
#define MAXBUF 200
#define SERVPORT 7777
int main()
{
char buf[MAXBUF];
sockaddr_in sin;
int sock,new_sock;
int dim;
bzero((char*)&sin,sizeof(sin));
sin.sin_family=AF_INET;
sin.sin_addr.s_addr=INADDR_ANY;
sin.sin_port=htons(SERVPORT);
if ((sock=socket(PF_INET,SOCK_STREAM,0))<0)
{
perror("server: errore in socket");
exit(1);
}
if (bind(sock,(sockaddr*)&sin,sizeof(sin))<0)
{
perror("server: errore in bind");
exit(1);
}
listen(sock,MAXCONN);
while (1)
{
if ((new_sock=accept(sock,(sockaddr *)&sin,(socklen_t *)&dim))<0)
{
perror("server: errore in accept");
exit(1);
}
while (dim=recv(new_sock,buf,sizeof(buf),0))
{
fputs(buf,stdout);
send(new_sock,buf,sizeof(buf),0);
}
close(new_sock);
}
return 0;
}
Nel client la porta locale non è scelta esplicitamente. Il comando netstat mi restituisce, ad esempio:
codice:
Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 192.168.211.142:7777 192.168.211.142:59834 ESTABLISHED
tcp 0 0 192.168.211.142:59834 192.168.211.142:7777 ESTABLISHED
(nota: le applicazioni le sto facendo girare sulla stessa macchina)
Si vede chiaramente il numero di porta del client, ovvero 59834, che non ho stabilito io e che cambia se rieseguo l'applicazione. Posso scoprire da programma (sia dal client che dal server) qual è questo numero di porta del client?
Ora spero davvero che la cosa sia chiara.