2 ** client.c -- a stream socket client demo
11 #include <sys/types.h>
12 #include <netinet/in.h>
13 #include <sys/socket.h>
15 #include <arpa/inet.h>
17 #define PORT "3490" // the port client will be connecting to
19 #define MAXDATASIZE 100 // max number of bytes we can get at once
21 // get sockaddr, IPv4 or IPv6:
22 void *get_in_addr(struct sockaddr
*sa
)
24 if (sa
->sa_family
== AF_INET
) {
25 return &(((struct sockaddr_in
*)sa
)->sin_addr
);
28 return &(((struct sockaddr_in6
*)sa
)->sin6_addr
);
31 int main(int argc
, char *argv
[])
34 char buf
[MAXDATASIZE
];
35 struct addrinfo hints
, *servinfo
, *p
;
37 char s
[INET6_ADDRSTRLEN
];
40 fprintf(stderr
,"usage: client hostname 'message'\n");
44 memset(&hints
, 0, sizeof hints
);
45 hints
.ai_family
= AF_UNSPEC
;
46 hints
.ai_socktype
= SOCK_STREAM
;
48 if ((rv
= getaddrinfo(argv
[1], PORT
, &hints
, &servinfo
)) != 0) {
49 fprintf(stderr
, "getaddrinfo: %s\n", gai_strerror(rv
));
53 // loop through all the results and connect to the first we can
54 for(p
= servinfo
; p
!= NULL
; p
= p
->ai_next
) {
55 if ((sockfd
= socket(p
->ai_family
, p
->ai_socktype
,
56 p
->ai_protocol
)) == -1) {
57 perror("client: socket");
61 if (connect(sockfd
, p
->ai_addr
, p
->ai_addrlen
) == -1) {
63 perror("client: connect");
71 fprintf(stderr
, "client: failed to connect\n");
75 if (send(sockfd
, argv
[2], strlen(argv
[2])+1, 0) == -1)
78 printf("connected\n");