Debian Codegraph @

COSMIC/Speername.c

raw
1 /* Speername.c: this function gets the name of the peer
2 * Authors: Charles E. Campbell, Jr.
3 * Terry McRoberts
4 * Copyright: Copyright (C) 1999-2005 Charles E. Campbell, Jr. {{{1
5 * Permission is hereby granted to use and distribute this code,
6 * with or without modifications, provided that this copyright
7 * notice is copied with it. Like anything else that's free,
8 * Speername.c is provided *as is* and comes with no warranty
9 * of any kind, either expressed or implied. By using this
10 * software, you agree that in no event will the copyright
11 * holder be liable for any damages resulting from the use
12 * of this software.
13 * Date: Aug 22, 2005
14 */
15 #include <stdio.h>
16 #include "sockets.h"
17
18 /* ---------------------------------------------------------------------
19 * Definitions:
20 */
21 #define PEERBUF 65
22
23 /* --------------------------------------------------------------------- */
24
25 /* Speername: get peername (a string) */
26 #ifdef __PROTOTYPE__
27 char *Speername(Socket *skt)
28 #else
29 char *Speername(skt)
30 Socket *skt;
31 #endif
32 {
33 static struct sockaddr_in sktname;
34 static char buf1[PEERBUF];
35 static char buf2[PEERBUF];
36 static char buf3[PEERBUF];
37 static char *buf = buf1;
38 #if defined(_AIX)
39 static size_t namelen = sizeof(struct sockaddr);
40 #elif defined(__gnu_linux__)
41 static socklen_t namelen = sizeof(struct sockaddr);
42 #else
43 static int namelen = sizeof(struct sockaddr);
44 #endif
45
46
47 if (buf == buf1) buf= buf2;
48 else if(buf == buf2) buf= buf3;
49 else buf= buf1;
50
51 /* sanity check */
52 if(!skt) strcpy(buf,"null socket");
53
54 /* attempt to get information from peer */
55 else if(getpeername(skt->skt,(struct sockaddr *) &sktname,&namelen) == -1) {
56 strcpy(buf,"unknown");
57 }
58 else {
59 struct hostent *host;
60
61 host= gethostbyaddr((void *) &(sktname.sin_addr.s_addr),sizeof(struct in_addr),AF_INET);
62
63 if(host && host->h_name) strcpy(buf,host->h_name);
64 else if(!host) strcpy(buf,"unable to get host");
65 else strcpy(buf,"unknown hostname");
66 }
67
68 return buf;
69 }
70
71 /* ===================================================================== */
72 #ifdef DEBUG_TEST
73
74 /* main: test routine begins here... */
75 int main(int argc,char **argv)
76 {
77 Socket *srvr = NULL;
78 Socket *skt = NULL;
79
80 rdcolor(); /* initialize color names (GREEN, RED, etc.) */
81
82 srvr= Sopen("GetPeerTest","S");
83 if(!srvr) error(XTDIO_ERROR,"unable to open <GetPeerTest> server\n");
84
85 skt = Saccept(srvr);
86
87 printf("client<%s> accepted, peer is <%s>\n",Sprtskt(skt),Speername(skt));
88
89 Sclose(skt);
90 Sclose(srvr);
91
92 return 0;
93 }
94
95 #endif /* DEBUG_TEST */
96
97 /* =====================================================================
98 * vim: ts=4
99 */