Back to index

glibc  2.9
getpeername.c
Go to the documentation of this file.
00001 /* Copyright (C) 1992,1994,1997,1999,2000,2005 Free Software Foundation, Inc.
00002    This file is part of the GNU C Library.
00003 
00004    The GNU C Library is free software; you can redistribute it and/or
00005    modify it under the terms of the GNU Lesser General Public
00006    License as published by the Free Software Foundation; either
00007    version 2.1 of the License, or (at your option) any later version.
00008 
00009    The GNU C Library is distributed in the hope that it will be useful,
00010    but WITHOUT ANY WARRANTY; without even the implied warranty of
00011    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00012    Lesser General Public License for more details.
00013 
00014    You should have received a copy of the GNU Lesser General Public
00015    License along with the GNU C Library; if not, write to the Free
00016    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
00017    02111-1307 USA.  */
00018 
00019 #include <errno.h>
00020 #include <string.h>
00021 #include <sys/socket.h>
00022 
00023 #include <hurd.h>
00024 #include <hurd/fd.h>
00025 #include <hurd/socket.h>
00026 
00027 /* Put the address of the peer connected to socket FD into *ADDR
00028    (which is *LEN bytes long), and its actual length into *LEN.  */
00029 int
00030 __getpeername (int fd, __SOCKADDR_ARG addrarg, socklen_t *len)
00031 {
00032   error_t err;
00033   mach_msg_type_number_t buflen = *len;
00034   int type;
00035   struct sockaddr *addr = addrarg.__sockaddr__;
00036   char *buf = (char *) addr;
00037   addr_port_t aport;
00038 
00039   if (err = HURD_DPORT_USE (fd, __socket_peername (port, &aport)))
00040     return __hurd_dfail (fd, err);
00041 
00042   err = __socket_whatis_address (aport, &type, &buf, &buflen);
00043   __mach_port_deallocate (__mach_task_self (), aport);
00044 
00045   if (err)
00046     return __hurd_dfail (fd, err);
00047 
00048   if (*len > buflen)
00049     *len = buflen;
00050 
00051   if (buf != (char *) addr)
00052     {
00053       memcpy (addr, buf, *len);
00054       __vm_deallocate (__mach_task_self (), (vm_address_t) buf, buflen);
00055     }
00056 
00057   const sa_family_t family = type;
00058   if (*len > offsetof (struct sockaddr, sa_family))
00059     {
00060       if (*len < (char *) (&addr->sa_family + 1) - (char *) addr)
00061        memcpy (&addr->sa_family, &family,
00062               *len - offsetof (struct sockaddr, sa_family));
00063       else
00064        addr->sa_family = family;
00065     }
00066 
00067   return 0;
00068 }
00069 
00070 weak_alias (__getpeername, getpeername)