833
|
1 #include <unistd.h>
|
841
|
2 #include <netinet/in.h>
|
|
3 #include <netdb.h>
|
833
|
4 #include <sys/types.h>
|
|
5 #include <sys/socket.h>
|
|
6
|
|
7 #include <stdio.h>
|
|
8
|
841
|
9 #include "network.h"
|
|
10
|
833
|
11 int
|
|
12 connect2Server(char *host, int port) {
|
|
13 int socket_server_fd;
|
|
14 struct sockaddr_in server_address;
|
841
|
15 printf(">>>> connect2Server [%s:%d]\n", host, port );
|
833
|
16 socket_server_fd = socket(AF_INET, SOCK_STREAM, 0);
|
|
17 if( socket_server_fd==-1 ) {
|
|
18 perror("Failed to create socket");
|
841
|
19 return -1;
|
833
|
20 }
|
|
21
|
|
22 if( isalpha(host[0]) ) {
|
841
|
23 struct hostent *hp =(struct hostent*)gethostbyname( host );
|
|
24 if( hp==NULL ) {
|
833
|
25 printf("Unknown host: %s\n", host);
|
841
|
26 return -1;
|
833
|
27 }
|
841
|
28 memcpy( (void*)&server_address.sin_addr.s_addr, (void*)hp->h_addr, hp->h_length );
|
833
|
29 } else {
|
|
30 inet_pton(AF_INET, host, &server_address.sin_addr);
|
|
31 }
|
|
32 server_address.sin_family=AF_INET;
|
|
33 server_address.sin_port=htons(port);
|
|
34
|
|
35 if( connect( socket_server_fd, (struct sockaddr*)&server_address, sizeof(server_address) )==-1 ) {
|
|
36 perror("Failed to connect to server");
|
841
|
37 close(socket_server_fd);
|
|
38 return -1;
|
833
|
39 }
|
|
40 return socket_server_fd;
|
|
41 }
|
|
42
|