-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocklib.c
More file actions
87 lines (80 loc) · 2.05 KB
/
socklib.c
File metadata and controls
87 lines (80 loc) · 2.05 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
/*************************************************************************
> File Name: socklib.c
> Author: jianghechao
> Mail: 591378033@qq.com
> Created Time: Mon 21 Apr 2014 12:13:04 AM CST
************************************************************************/
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
#include<time.h>
#include<string.h>
#define HOSTLEN 256
#define BACKLOG 1
int make_server_socket_q(int ,int);
int make_server_socket(int portnum)
{
return make_server_socket_q(portnum,BACKLOG);
}
int make_server_socket_q(int portnum,int backlog)
{
fprintf(stdout,"The portnum is %d\n",portnum);
struct sockaddr_in saddr;
struct hostent *hp;
char hostname[HOSTLEN];
int sock_id;
sock_id = socket(AF_INET,SOCK_STREAM,0);
if(sock_id==-1)
{
fprintf(stderr,"socket error in socklib\n");
return -1;
}
fprintf(stderr,"socket success in socklib\n");
bzero((void*)&saddr,sizeof(saddr));
/* gethostname(hostname,HOSTLEN);
fprintf(stdout,hostname);
hp = gethostbyname(hostname);
if(hp==NULL)
{
fprintf(stderr,"gethostbyname error in socklib\n");
return -1;
}
bcopy((void*)hp->h_addr,(void *)&saddr.sin_addr,hp->h_length);
*/
saddr.sin_addr.s_addr = inet_addr("192.168.56.101");
saddr.sin_port = htons(portnum);
saddr.sin_family = AF_INET;
if(bind(sock_id,(struct sockaddr *)&saddr,sizeof(saddr))!=0)
{
fprintf(stderr,"bind error in socklib\n");
return -1;
}
if(listen(sock_id,backlog)!=0)
{
fprintf(stderr,"listen error in socklib\n");
return -1;
}
return sock_id;
}
int connect_to_server(char *host, int portnum)
{
int sock;
struct sockaddr_in servadd;
struct hostent *hp;
sock = socket(AF_INET,SOCK_STREAM,0);
if(sock==-1)
return -1;
bzero(&servadd,sizeof(servadd));
hp = gethostbyname(host);
if(hp==NULL)
return -1;
bcopy(hp->h_addr,(struct sockaddr*)&servadd.sin_addr,hp->h_length);
servadd.sin_port = htons(portnum);
servadd.sin_family = AF_INET;
if(connect(sock,(struct sockaddr*)&servadd,sizeof(servadd))!=0)
return -1;
return sock;
}