This repository has been archived by the owner on Nov 5, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pipe.c
63 lines (52 loc) · 1.41 KB
/
pipe.c
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
/*********************************************
* pipe.c
* Socket Code for Text-Based Adventure Game
* COMP3411 Artificial Intelligence
* UNSW Session 1, 2016
*/
// YOU SHOULD NOT NEED TO MODIFY THIS FILE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/tcp.h>
#include <netdb.h>
int tcpopen(char *host, int port)
{
int sd, rc;
struct hostent *h;
//struct sockaddr_in localAddr, servAddr;
struct sockaddr_in servAddr;
h = (struct hostent *)gethostbyname(host);
if(h==NULL) {
printf("unknown host '%s'\n",host);
exit(1);
}
servAddr.sin_family = h->h_addrtype;
memcpy((char *) &servAddr.sin_addr.s_addr,h->h_addr_list[0],h->h_length);
servAddr.sin_port = htons(port);
/* create socket */
sd = socket(AF_INET, SOCK_STREAM, 0);
if(sd<0) {
perror("cannot open socket ");
exit(1);
}
/* bind any port number */
//localAddr.sin_family = AF_INET;
//localAddr.sin_addr.s_addr = htonl(INADDR_ANY);
//localAddr.sin_port = htons(0);
int tcp_no_delay = 1;
if(setsockopt(sd, IPPROTO_TCP, TCP_NODELAY,
(char *)&tcp_no_delay, sizeof(tcp_no_delay)) < 0) {
perror ("tcpecho: TCP_NODELAY options");
exit(1);
}
/* connect to server */
rc = connect(sd, (struct sockaddr *) &servAddr, sizeof(servAddr));
if(rc<0) {
perror("cannot connect ");
exit(1);
}
return sd;
}