-
Notifications
You must be signed in to change notification settings - Fork 0
/
mysocks.c
executable file
·105 lines (83 loc) · 2.05 KB
/
mysocks.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
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
102
103
104
105
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <netdb.h>
#include <strings.h>
#include <errno.h>
#define QLEN 5
int myServerSocket( int port ){
int s, retcode;
struct sockaddr_in sin;
bzero( (char *)&sin, sizeof(sin));
sin.sin_family=AF_INET;
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_port = htons((ushort)port);
s = socket( PF_INET, SOCK_STREAM, 0);
if( s < 0){
//printf("unable to create serverSocket\n");
return -1;
}
retcode = bind( s, (struct sockaddr *)&sin, sizeof(sin));
if( retcode < 0){
// printf("unable to bind serverSocket to port %d\n",
// port);
return -1;
}
retcode = listen( s, QLEN);
if( retcode < 0){
// printf("unable to make listen on serverSocket\n");
return -1;
}
return s;
}
int myAcceptServerSocket( int s){
int csock, clen;
struct sockaddr_in csin;
csock = accept( s, NULL, NULL);
if( csock < 0){
// printf("unable to complete accept\n");
perror("Accept");
return -1;
}
return csock;
}
int myConnectSocket(char *hostname, int port){
int s, retcode;
struct sockaddr_in sin;
struct hostent *serv;
bzero( (char *)&sin, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons((u_short)port);
serv = gethostbyname(hostname);
if( serv ==NULL){
//printf("unable to obtain an IP address for %s\n",
// hostname);
return -1;
}
bcopy( serv->h_addr, (char *)&sin.sin_addr, serv->h_length);
s = socket(PF_INET, SOCK_STREAM, 0);
if( s < 0) {
// printf("unable to create client socket\n");
return -1;
}
retcode = connect( s, (struct sockaddr *)&sin, sizeof(sin));
if(retcode <0) {
//printf("unable to connect to host %s, port %d\n",
// hostname, port);
return -1;
}else return s;
}
int myWriteSocket( int s, char *buf, int nw){
return write(s, buf, nw);
}
int myReadSocket( int s, char *buf, int max){
int n;
n = read( s, buf, max);
return n;
}
void myCloseSocket( int s ){
close(s);
}