Função getpeername

Sintaxe:

#include <sys/socket.h>

int getpeername(int iSocket, struct sockaddr * stNome, socklen_t * iTamanho_nome);


A função getpeername retorna o nome de um cliente que conectou­-se ao servidor. A função retorna 0 (zero) em caso de sucesso ou –1 se houve algum erro.

Veja o exemplo:

#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
 
int main(void)
{
   int iSock;
   struct sockaddr_in my_addr;
 
   iSock = socket(AF_INET, SOCK_STREAM, 0);
   if( iSock == -1)
   {
      perror("socket:");
      exit(1);
   }
 
   my_addr.sin_family = AF_INET;
   my_addr.sin_port = htons(4950);
   my_addr.sin_addr.s_addr = INADDR_ANY;
   bzero(&(my_addr.sin_zero), 8);
 
   if( bind(iSock, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1)
   {
      perror("bind:");
      exit(1);
   }
 
   if( listen( iSock, 10 ) < 0)
   {
      perror("listen:");
      exit(1);
   }
   while(1)
   {
      int iFd;
      struct sockaddr_in client_addr;
      struct sockaddr_in client_peer;
      socklen_t sin_size;
      socklen_t len_peer;
      int port;
      char ipstr[INET_ADDRSTRLEN];
 
      sin_size = sizeof(struct sockaddr_in);
 
      if( (iFd = accept(iSock, (struct sockaddr *) &client_addr, &sin_size)) < 0)
      {
         perror("accept:");
         exit(1);
      }
 
      printf("\nServidor recebeu conexao de %s", inet_ntoa(client_addr.sin_addr)); /* identifica a origem da conexão */
 
 
      len_peer = sizeof(client_peer);
 
      getpeername(iFd, (struct sockaddr *)&client_peer, &len_peer);
 
      port = ntohs(client_peer.sin_port);
      inet_ntop(AF_INET, &client_peer.sin_addr, ipstr, sizeof(ipstr));
 
      printf("\nNome do cliente: %s", ipstr);
      printf("\nPorta do cliente: %d", port);
      close(iFd);
   }
   return 0;
}

Programa que só se conecta no servidor e já finaliza.

/* teste_getpeername.c */
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
 
int main(void)
{
   int iSock;
   int iBytes;
   struct sockaddr_in dest_addr;
   char buffer[100];
 
   iSock = socket(AF_INET, SOCK_STREAM, 0);
   if( iSock == -1)
   {
      perror("socket:");
      exit(1);
   }
 
   dest_addr.sin_family = AF_INET;
   dest_addr.sin_port = htons(4950);
   dest_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
   bzero(&(dest_addr.sin_zero), 8);
 
   if( connect(iSock, (struct sockaddr *)&dest_addr, sizeof(struct sockaddr)) < 0)
   {
      perror("connect:");
      exit(1);
   }
 
   return 0;
}

Marcos Laureano 2009/03/11 17:14

getpeername.txt · Última modificação: 2009/03/11 17:07 por laureano
CC Attribution-Noncommercial-Share Alike 3.0 Unported
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0