-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhelloc.c
More file actions
101 lines (87 loc) · 2.01 KB
/
Copy pathhelloc.c
File metadata and controls
101 lines (87 loc) · 2.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdarg.h>
#include <string.h>
#include <errno.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "skel.h"
char *program_name;
/* error - print a diagnostic and optionally exit */
void error( int status, int err, char *fmt, ... )
{
va_list ap;
va_start( ap, fmt );
fprintf( stderr, "%s: ", program_name );
vfprintf( stderr, fmt, ap );
va_end( ap );
if ( err )
fprintf( stderr, ": %s (%d)\n", strerror( err ), err );
if ( status )
EXIT( status );
}
/* set_address - fill in a sockaddr_in structure */
static void set_address( char *hname, char *sname,
struct sockaddr_in *sap, char *protocol )
{
struct servent *sp;
struct hostent *hp;
char *endptr;
short port;
bzero( sap, sizeof( *sap ) );
sap->sin_family = AF_INET;
if ( hname != NULL )
{
if ( !inet_aton( hname, &sap->sin_addr ) )
{
hp = gethostbyname( hname );
if ( !hp )
error( 1, 0, "unknown host: %s\n", hname );
sap->sin_addr = *( struct in_addr * )hp->h_addr;
}
}
else
sap->sin_addr.s_addr = htonl( INADDR_ANY );
port = strtol( sname, &endptr, 0 );
if ( *endptr == '\0' )
sap->sin_port = htons( port );
else
{
sp = getservbyname( sname, protocol );
if ( !sp )
error( 1, 0, "unknown service: %s\n", sname );
sap->sin_port = sp->s_port;
}
}
/* client - place holder for the client code */
static void client( SOCKET s, struct sockaddr_in *peerp )
{
int rc;
char buf[ 120 ];
for ( ;; )
{
rc = recv( s, buf, sizeof( buf ), 0 );
if ( rc <= 0 )
break;
write( 1, buf, rc );
}
}
/* main - connect to the server */
int main( int argc, char **argv )
{
struct sockaddr_in peer;
SOCKET s;
INIT();
set_address( argv[ 1 ], argv[ 2 ], &peer, "tcp" );
s = socket( AF_INET, SOCK_STREAM, 0 );
if ( !isvalidsock( s ) )
error( 1, errno, "socket call failed" );
if ( connect( s, ( struct sockaddr * )&peer,
sizeof( peer ) ) )
error( 1, errno, "connect failed" );
client( s, &peer );
EXIT( 0 );
}